Child with max-height: 100% overflows parent

.container {
  background: blue;
  padding: 10px;
  max-height: 200px;
  max-width: 200px;
  float: left;
  margin-right: 20px;
}

.img1 {
  display: block;
  max-height: 100%;
  max-width: 100%;
}

.img2 {
  display: block;
  max-height: inherit;
  max-width: inherit;
}
<!-- example 1  -->
<div class="container">
  <img class='img1' src="http://via.placeholder.com/350x450" />
</div>

<!-- example 2  -->

<div class="container">
  <img class='img2' src="http://via.placeholder.com/350x450" />
</div>

I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

.container {
    background: blue;
    padding: 10px;
    max-height: 100px;
    max-width: 100px;
    text-align:center;
}

img {
    max-height: inherit;
    max-width: inherit;
}

When you specify a percentage for max-height on a child, it is a percentage of the parent's actual height, not the parent's max-height, oddly enough. The same applies to max-width.

So, when you don't specify an explicit height on the parent, then there's no base height for the child's max-height to be calculated from, so max-height computes to none, allowing the child to be as tall as possible. The only other constraint acting on the child now is the max-width of its parent, and since the image itself is taller than it is wide, it overflows the container's height downwards, in order to maintain its aspect ratio while still being as large as possible overall.

When you do specify an explicit height for the parent, then the child knows it has to be at most 100% of that explicit height. That allows it to be constrained to the parent's height (while still maintaining its aspect ratio).

Tags:

Css