【问题标题】:Centering images within 300 px by 300 px table grid将 300 像素 x 300 像素表格网格内的图像居中
【发布时间】:2012-09-04 21:20:41
【问题描述】:

我的代码在下面,我正在寻找通过 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,其中图像居中。

【问题讨论】:

  • 这里有一些解决方案,虽然我不确定你是否能够实现它们:blog.themeforest.net/tutorials/vertical-centering-with-css
  • 您需要div 环绕img 吗?您可以将vertical-aligntext-align 添加到td,这样就可以了。
  • 另外,类名不应该以数字开头试试.box300
  • 抛弃 div 和 image 类,直接将 .300box 和 .centeredimage 样式应用到你的 ...
  • 这种技术不起作用,图像水平居中而不是垂直居中。垂直部分似乎没有粘住。

标签: html css html-table centering


【解决方案1】:

让你的代码完全一样,改变这个样式定义:

.centeredimage {
  margin: auto;
}

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

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

【讨论】:

  • 这种技术不起作用,图像水平居中但不是垂直居中。垂直部分似乎没有粘住。
  • 可以附上截图吗?并且:对于垂直居中,您希望每个图像在其表格单元格中居中,并且该行中的图像可能具有不同的大小,对吗?
【解决方案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>

【讨论】:

  • 这很好,谢谢。但是现在如果我想在每个图像下方添加一个文本块,如果图像小于 300 像素,则文本将显示在图像的正下方。我该怎么做才能将图像的所有文本强制到表格单元格的底部?
猜你喜欢
相关资源
最近更新 更多
热门标签