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

Aar*_*sen 5 html css html-table html-email

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

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

img {
  display: block;
  width: 25px;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

如何使图像填充其单元格的高度?

Tem*_*fif 3

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

.img {
  width: 25px;
  background-size:100% 100%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

.img {
  width: 25px;
  position:relative;
}
.img img {
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)