Dave_K Dave_K - 4 months ago 16
CSS Question

IMG in table cell, force max-size but maintain aspect ratio and responsiveness

I have a table with an image in the first cell and text in the next. The page will be viewed with all devices, so I need to keep responsiveness (and the table).

Everything seemed to work - images were centered, are responsive, etc. BUT, some images are just too tall. So I set a max height, but now the images lose aspect ratio.

IF I set the width and height to auto I lose responsiveness, and I can't find a solution that keeps the aspect ratio, sets max width and height and still maintains responsiveness, any pointers?



table {
width: 90%;
max-width:800px;
}

table td {
padding:10px;
border-bottom:solid black 2px;
text-align:center;
vertical-align:middle;
}
table td:first-child {
width: 50%;
}
table td img {
max-width:180px;
max-height:70px;
}

<table>
<tr>
<td>
<img src="http://source.of.image.com" width="100%" />
</td>
<td>
Blah Blah
</td>
</tr>
<tr>
<td>
<img src="https://www.google.com/images/srpr/logo3w.png" width="100%"/>
</td>
<td>
Blah Blah
</td>
</tr>
</table>




Answer

Does it work when you set a max-width, a max-height and set the width to auto. It seems to work in your snippet.

Edit: Version 2

  1. Is this the effect you want?
  2. Can you move the img to the background of the td?

table {
  width: 90%;
  max-width:800px;
  }

table td {
  padding:10px;
  border-bottom:solid black 2px;
  text-align:center;
  vertical-align:middle;
}
table td:first-child {
  width: 70%;
  max-width:180px;
  max-height:70px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  background-origin: padding-box;
  }
<table>
  <tr>
    <td style="background-image: url(http://goo.gl/QrKCc);">
    </td>
    <td>
      Blah Blah
    </td>
  </tr>
  <tr>
    <td style="background-image: url(http://goo.gl/QrKCc);">
    </td>
    <td>
      Blah Blah<br />
      A forced second line to increase the height
    </td>
  </tr>
  <tr>
    <td style="background-image: url(https://www.google.com/images/srpr/logo3w.png)"> 
    </td>
    <td>
      Blah Blah
    </td>
  </tr>
</table>

Comments