Why Does Height: 100% on a Child Element Fail to Apply When the Parent Element Has a Min-Height/Max-Height Value but No Specified Height Value?
Consider the following HTML and CSS setup:
<div class="container"> <div class="child"></div> </div>
.container { background-color: red; width: 500px; min-height: 300px; } .child { background-color: blue; width: 500px; height: 100%; }
In this scenario, the container element renders with a height of 300px as expected, but the child element remains without any height despite the height: 100% declaration.
However, adding a small height value (e.g., 1px) to the container element causes the child element to suddenly fill the entire container with a height of 300px:
.container { background-color: red; width: 500px; min-height: 300px; height: 1px; } .child { background-color: blue; width: 500px; height: 100%; }
This behavior stems from the CSS specification itself. When an element's height is not explicitly defined, the percentage height on its child will fail. According to the spec:
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.
In the initial case, since the container element's height is not explicitly set, the child element's height: 100% becomes 'auto'. This means it will take up only as much space as its content requires, resulting in no visible height.
Adding a height value (even as small as 1px) to the container element explicitly defines its height, allowing the child element's height: 100% to calculate and apply the correct height.
Therefore, the seemingly unexpected behavior stems from the fact that the height of a parent element needs to be explicitly defined for its child elements to correctly calculate their percentage heights.
The above is the detailed content of Why Does `height: 100%` Fail on a Child Element When Its Parent Has `min-height`/`max-height` but No Explicit Height?. For more information, please follow other related articles on the PHP Chinese website!