Consider a situation where you have a child element with a max-height of 100% inside a container that also utilizes max-height. Unexpectedly, the child element ends up overflowing the parent.
Understanding the Behavior
The issue stems from the fact that when you define a percentage for max-height on a child, it refers to a percentage of the parent's actual height, not its max-height. Thus, when the parent element does not have an explicit height set, there is no defined base height for the child element's max-height calculation. Consequently, max-height defaults to "none," allowing the child element to grow indefinitely.
In this case, the only restriction on the child is the max-width of its parent. Since the image is taller than it is wide, it overflows the container's height in the downward direction to maintain its aspect ratio while maximizing its overall size.
Solution: Explicit Height
To resolve this issue, you simply need to provide an explicit height to the parent element. By doing so, you establish a clear base height for the child element's max-height calculation. As a result, the child element will be confined to the parent's height while still maintaining its aspect ratio.
Therefore, specifying an explicit height for the parent element ensures that the child element respects its max-height restriction, preventing it from overflowing the container.
The above is the detailed content of Why Does My Child Element Overflow Its Parent Despite Both Having `max-height: 100%`?. For more information, please follow other related articles on the PHP Chinese website!