0

我的代码在下面,我正在寻找通过 CSS 将图像(水平和垂直)居中在 300 x 300 像素正方形中的最佳方法。较大的图像将适合该尺寸,较小的图像应居中,而不是拉伸。

<table width="100%">
  <tr>
    <td><div class="300box"><img class="centeredimage" /></div></td>
    <td><div class="300box"><img class="centeredimage" /></div></td>
    <td><div class="300box"><img class="centeredimage" /></div></td>
  </tr>
</table>

CSS:

.300box {
  height: 300px;
  width: 300px;
}

.centeredimage {
  vertical-align: middle;
  text-align: center;
}

我知道以上是不正确的,所以我希望找到一种更有效的方法来做到这一点。每个表格行都有 3 个 300x300 像素的 div,其中图像居中。

4

2 回答 2

2

在 td 中使用 div 并不比任何其他使用表格的方式差。

你可以试试这个——

CSS:

.blocks.table td {
    width: 300px;
    height: 300px;
    border: 1px solid #ff0000;
    vertical-align: middle;
    text-align: center;
}
p.centeredimage img {
    max-height: 300px;
    max-width: 300px;
}

HTML:

<table width="100%" class="table blocks">
    <tr>
        <td>
            <p class="centeredimage" ><img src = "http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/185106_431273290248855_254736287_n.jpg" /></p>
        </td>

        <td>
            <p class="centeredimage" ><img src = "http://a6.sphotos.ak.fbcdn.net/hphotos-ak-ash4/304640_10151181184992355_456123210_n.jpg" /></p>
        </td>
        <td>
            <p class="centeredimage" ><img src = "http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc7/s480x480/422953_410146439043183_1035950087_n.jpg" /></p>
        </td>
        <td>
            <p class="centeredimage" ><img src = "http://sphotos-e.ak.fbcdn.net/hphotos-ak-ash3/s480x480/561574_467101546644877_728463753_n.jpg" /></p>
        </td>
    </tr>
</table>
于 2012-09-13T06:16:45.657 回答
0

保持您的代码完全相同,更改这一样式定义:

.centeredimage {
  margin: auto;
}

你说你想让更大的图像被强制不超过 300 像素?我知道 max-width 属性有时会起作用(当然 IE8 非常不喜欢它),但我不知道它在图像上的效果如何(我自己从未测试过),但要补充一点,你只是将 max-width: 300px 添加到 centeredimage 类。

经过反思,其他人所说的也适用:将您的 .300box 类应用于 td,并摆脱 div。对于您所描述的,它们不是必需的。

于 2012-09-11T21:49:05.533 回答