Aaron Christiansen
Aaron Christiansen

Reputation: 11807

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?

Upvotes: 5

Views: 2803

Answers (2)

gwally
gwally

Reputation: 3537

With email clients such as Outlook desktop 2007-2019, you need to specify the width of the image, especially if you are displaying it in a size that does not match it's physical size. Otherwise Outlook will ignore your style sheet and revert to the actual size.

For the height, you can generally leave it blank and add in the style sheet height: auto;

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

Good luck.

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272789

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>

Upvotes: 3

Related Questions