Chris Rowley
Chris Rowley

Reputation: 25

Constrain an img inside div with max-height, width auto

This simple bit of code works great in WebKit browsers but fails in IE and Firefox. I need to use the img tag for other functionality so background-image is not an option.

Snippet

img {
  max-width: 100%;
  height: auto;
}
.vgp-dtable {
  width: 100%;
  max-width: 860px;
  margin: 0 auto 1em;
  display: table;
}
.vgp-dtable .row {
  display: table-row;
}
.vgp-dtable .row .art,
.vgp-dtable .row .txt {
  display: table-cell;
  vertical-align: top;
}
.vgp-dtable .row .art {
  width: 30%;
  text-align: right;
}
.vgp-dtable .row .art img {
  width: auto;
  max-height: 280px;
}
.vgp-dtable .row .txt {
  width: 70%;
  text-align: left;
  padding-left: 8px;
}
<div class="vgp-dtable">
  <div class="row">
    <div class="art">
      <img src="http://vgpavilion.com/mags/1982/12/vg/ads/003-004-005_tn.jpg">
    </div>
    <div class="txt">
      <p>Here's some sample text.</p>
    </div>
  </div>
  <a id="riddle-of-the-sphinx"></a>
  <div class="row">
    <div class="art">
      <img src="http://vgpavilion.com/mags/1982/12/vg/thumbs/007.jpg">
    </div>
    <div class="txt">
      <p>Here's some sample text.</p>
    </div>
  </div>
</div>

In WebKit the images properly resize to fit the 30% wide container block with a maximum height of 280px. In Firefox and IE, however, only the max-height is respected and the images force their container to become wider than 30%.

A simple example here. The simple example has a working version using a float method above the broken display:table implementation.

You can see the full page here

I have tried a number of combinations of containers and the images will never respect the width unless specified in absolute terms when in Firefox or IE. In a previous instance I went with the background-image solution that works in all tested browsers but really didn't want to. I found a solution by using a float rather than display: table-cell but it's confounding me that it is broken using a nearly identical table method in IE and Firefox so perhaps someone out there can spot something I'm missing or that I shouldn't have added.

Upvotes: 2

Views: 405

Answers (1)

dippas
dippas

Reputation: 60553

simply add table-layout:fixed here:

.vgp-dtable {
  width: 100%;
  max-width: 860px;
  margin: 0 auto 1em;
  display: table;
  table-layout: fixed  /*added*/
}

Upvotes: 1

Related Questions