【问题标题】:Stretching an image to fill the height of its table cell拉伸图像以填充其表格单元格的高度
【发布时间】:2019-07-30 14:21:45
【问题描述】:

我有一个高度未知的表格单元格,其中包含img。这个img 有一个固定的像素宽度,但我需要它拉伸以填充(但不超过)表格单元格的整个高度。无论高度如何,宽度都应保持不变。

通常,我会使用height: 100% 来执行此操作,但这在这种情况下似乎不起作用:

img {
  display: block;
  width: 25px;
  height: 100%;
}
<table>
  <tr>
    <td>
      Here is some content.<br/>
      I would like the adjacent image to stretch to be<br/>
      the same height as it, but not have the image get<br/>
      any wider.
    </td>
    <td>
      <img src="https://placehold.it/20x20" />
    </td>
  </tr>
</table>

如何让图片填满其单元格的高度?

【问题讨论】:

  • 如果您将高度作为属性添加到图像(不是 CSS)上,它可能会满足您的需求。 &lt;img src="https://placehold.it/20x20" height="100%" width="25" /&gt; 但是下面的CSS背景答案是更灵活的解决方案。

标签: html css html-table html-email


【解决方案1】:

将图像视为背景,您可以轻松实现这一点。您还可以将background-image 保留为内联样式,以便能够将其设置为img 元素

.img {
  width: 25px;
  background-size:100% 100%;
}
<table>
  <tr>
    <td>
      Here is some content.<br/>
      I would like the adjacent image to stretch to be<br/>
      the same height as it, but not have the image get<br/>
      any wider.
    </td>
    <td class="img" style="background-image:url(https://placehold.it/20x20)">
    </td>
  </tr>
</table>

如果你想继续使用img,你可以使用position:absolute

.img {
  width: 25px;
  position:relative;
}
.img img {
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
}
<table>
  <tr>
    <td>
      Here is some content.<br/>
      I would like the adjacent image to stretch to be<br/>
      the same height as it, but not have the image get<br/>
      any wider.
    </td>
    <td class="img">
      <img src="https://placehold.it/20x20)"/>
    </td>
  </tr>
</table>

【讨论】:

  • 这是一种非常干净的方法!谢谢。
  • @AaronChristiansen 添加了另一种方法
  • @TemaniAfif 电子邮件客户端(如 Outlook)无法正确呈现。这是用于 HTML 电子邮件而不是用于网络。
【解决方案2】:

对于 Outlook 桌面 2007-2019 等电子邮件客户端,您需要指定图像的宽度,尤其是当您以与其物理尺寸不匹配的尺寸显示图像时。否则 Outlook 将忽略您的样式表并恢复为实际大小。

高度一般可以留空,在样式表中添加height: auto;

<img src="https://placehold.it/20x20)" width="20" height="" alt="" border="0" style="height: auto;">

祝你好运。

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多