Search code examples
htmlcsshtml-tablehtml-email

Stretching an image to fill the height of its table cell


I have a table cell of unknown height which contains an img. This img has a fixed pixel width, but I need it to stretch to fill (but not exceed) the entire height of the table cell. The width should remain the same no matter what the height.

Usually, I'd do this using height: 100%, but this doesn't appear to be working in this scenario:

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>

How can I make the image fill the height of its cell?


Solution

  • Consider the image as background and you can easily achieve this. You can also keep the background-image as an inline style to be able to set it like an img element

    .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>

    In case you want to keep the use of img you can use 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>