I'm trying to understand what appears to be unexpected behaviour to me:
I have an element with a max-height of 100% inside a container that also uses a max-height but, unexpectedly, the child overflows the parent:
Test case: http://jsfiddle.net/bq4Wu/16/
.container {
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
}
img {
display: block;
max-height: 100%;
max-width: 100%;
}
This is fixed, however, if the parent is given an explicit height:
Test case: http://jsfiddle.net/bq4Wu/17/
.container {
height: 200px;
}
Does anyone know why the child would not honour the max-height of its parent in the first example? Why is an explicit height required?
When you specify a percentage for
max-height
on a child, it is a percentage of the parent's actual height, not the parent'smax-height
, oddly enough. The same applies tomax-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, somax-height
computes tonone
, allowing the child to be as tall as possible. The only other constraint acting on the child now is themax-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).
Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the
width
of the image appears before theheight
.A good solution is to not use height on the parent and use it just on the child with View Port :
Fiddle Example: https://jsfiddle.net/voan3v13/1/