In CSS, the height property can be a perplexing conundrum when it comes to using percentage values. Unlike its counterpart, width, which scales effortlessly to a parent element's size, percentage height values often result in unexpected behavior.
Consider the following HTML and CSS:
<div>
#working { width: 80%; height: 140px; background: orange; } #not-working { width: 80%; height: 30%; background: green; }
While the width of #working calculates to 80% of the viewport as expected, the height of #not-working puzzlingly becomes 0.
The crux of this issue lies in the default height of block elements like div. By default, the height of a block element conforms to the size of its content. This creates a feedback loop:
<div>
Here, #inner expands to fit the paragraph within it, while #outer grows to accommodate #inner.
Percentage height values add another layer to this relationship. When specifying a percentage height, for example 30%, it refers to the parent element's height. However, the parent element's height is influenced by the height of its child elements, leading to a circular dependency.
To resolve this dilemma, the feedback loop must be broken. This can be achieved by explicitly setting the height of the parent element, effectively removing its dependence on its child elements. For instance, in the above example, adding #outer { height: 500px; } would provide a well-defined calculation for both #outer and #not-working.
In conclusion, while percentage width values work seamlessly due to the independent nature of width for block elements, percentage height calculations are inherently tied to the content and require a clear height definition for the parent element.
The above is the detailed content of Why Does Percentage Height in CSS Sometimes Result in Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!