0

如何将div与另一个div对齐并将其集中在表格中?

echo '<table border="0" cellspacing="1" cellpadding="7" width="100%">';
    echo '<tr bgcolor="'.$config['site']['purple'].'">';
        echo '<td align="center">';
            foreach($image as $img){
                echo '<div style="width:24%;height:130px;position:relative;float:left;margin:2px auto;background-image:url('.$img['location'].');background-size:100%;"></div>';
            }
        echo '</td>';
    echo '</tr>';
echo '</table>';

我将div完美地放在一边,但它仍然在左侧<td>而不是在中心。

如何解决?

4

1 回答 1

1

检查这个 JSfiddle。您需要的格式比我想象的要少:p

http://jsfiddle.net/5c2Vj/

注意:出于测试目的,我手动添加了一些 div。

HTML

<table border="0" cellspacing="1" cellpadding="7" width="100%">
    <tr bgcolor="purple">
        <td align="center">
            <div class="image" style="background-image: url(https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png)"></div>
            <div class="image" style="background-image: url(https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png)"></div>
            <div class="image" style="background-image: url(https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png)"></div>
            <div class="image" style="background-image: url(https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png)"></div>
            <div class="image" style="background-image: url(https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png)"></div>
        </td>
    </tr>
</table>

CSS

div.image {
    display: inline-block;
    width: 24%;
    height:130px;
    border: 1px solid black; /* For visual reference */
}

多亏align="center"了 TR 元素,div 居中。
当您清理代码(将 HTML 与样式分开)时,您也可以在该行上使用 CSS 类。


编辑:

我做了一个小测试(没有 CSS 类)。

$config['site']['purple'] = "purple";
$image = array(
    'StackOverflow' => 'https://stackoverflow.com/content/stackoverflow/img/apple-touch-icon.png',
    'W3C' => 'http://www.propra.nl/img/w3c.png',
    'CSS' => 'http://a.dryicons.com/images/icon_sets/coquette_part_5_icons_set/png/128x128/css_file.png',
    'HTML' => 'http://a.dryicons.com/images/icon_sets/coquette_part_5_icons_set/png/128x128/html_file.png',
    'LifeIsPain' => 'http://oldpunks.com/1iconlifeispain.gif'
);

echo '<table border="0" cellspacing="1" cellpadding="7" width="100%">
    <tr bgcolor="'.$config['site']['purple'].'">
        <td align="center">';
            foreach($image as $name => $location){
                echo '<div style="display: inline-block; width: 24%; height:130px; border: 1px solid black; background-image:url('.$location.');background-size:100%;"></div>';
            }
        echo '</td>
    </tr>
</table>';
于 2014-03-05T22:21:56.567 回答