拉伸图像以填充其表格单元格的高度

5

我有一个高度未知的表格单元格,其中包含一个 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),它可能会达到您想要的效果。 <img src =“https://placehold.it/20x20”height =“100%”width =“25”/> 但下面的CSS背景答案是更灵活的解决方案。 - Bryce Howitson
2个回答

3
考虑将图片作为背景,您可以轻松实现这一点。您还可以将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>


这是一种非常干净的做法!谢谢。 - Aaron Christiansen
@AaronChristiansen 添加了另一个方法。 - Temani Afif
1
@TemaniAfif 像Outlook这样的电子邮件客户端无法正确呈现它。这是针对HTML电子邮件而不是Web的。 - Syfer

0

对于像Outlook桌面版2007-2019这样的电子邮件客户端,如果您要显示的图像大小与其实际大小不匹配,则需要指定图像的宽度。否则,Outlook将忽略您的样式表并恢复到实际大小。

对于高度,通常可以将其留空,并在样式表中添加height: auto;

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

祝你好运。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接