charles
charles

Reputation: 1874

img { max-height: 100%; } causes img to exceed bounds

Is this a Chrome bug?

Here's the HTML:

<div><img src="test.png"></div>

Here's the CSS:

* { box-sizing: border-box; }
div { height: 200px; padding: 75px 0 60px; }
img { max-height: 100%; }

Expected result: The img should have a height of 65px.

Result in Chrome (v. 27.0.1453.116) on Mac OS (v. 10.6.8): The img has height of 135px and "bleeds" into the parent div's padding. If I change the padding of the div to 50px 0, oddly it renders properly.

Play with this in a codepen: http://codepen.io/anon/pen/jhbKz

Screenshots:

First block has padding of 50px 0. Second block has padding of 75px 0 60px.

Firefox (correct result)

Firefox

Chrome (wrong?)

Chrome

Upvotes: 15

Views: 9643

Answers (3)

Pavel Laptev
Pavel Laptev

Reputation: 73

You can achieve it using position: absolute for your image.

<div class="wrap">
  <img class="img" src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-2500.jpg" alt="">
</div>
body {
  height: 100vh;
}

.wrap {
  display: inline-block;
  position: relative;
  max-height: 500px;
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.1);
}

.img {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  height: 100%;
}

jsfiddle

Upvotes: 0

Ralf
Ralf

Reputation: 729

Years later, the issue seems to have spread to Firefox. Pav's workaround did not work for me, maybe because I have "a" not "div". The only way in my case was to display as table:

<div style="display: table;">
<a style="height: 100px; display: table-cell;" href="#">
    <img style="max-height: 100%; width: auto;" src="some image url">
</a></div>

An additional benefit of "table" is that vertical-align: middle; can be used to center the image (or other content) vertically.

Upvotes: 0

Pav
Pav

Reputation: 1166

Try adding a container to your Image with width and height of 100%. This will give you the same output on chrome and FF.

<div class="b">
    <div style='height:100%;width:100%;'>
        <img src="some image url">
    </div>
</div>

I cannot explain why this fix works currently, but I myself am trying to reason with it.

Upvotes: 6

Related Questions