In CSS, a percentage value for width works as expected, but the same doesn't hold true for height. To understand this behavior, we need to examine the default height calculations of block elements.
Default Height Calculation:
The height of a block element is determined by its content. If the element contains text, images, or other block elements, its height will grow to accommodate the content.
Percentage Width vs. Percentage Height:
When you specify a percentage width, the element's width is calculated as a percentage of its parent's width. Since block elements are inherently as wide as their parent, this calculation yields a well-defined value in pixels.
However, the height of a block element is dependent on its content. Specifying height: 50% creates ambiguity because it's not clear what 50% of the parent's height should be when the element's own content can potentially vary its height.
Breaking the Feedback Loop:
To solve this ambiguity, you need to break the feedback loop between parent and child. This can be done by explicitly specifying the parent element's height.
For example:
#parent { height: 200px; } #child { height: 50%; /* Now calculates 50% of #parent's height */ }
By providing a specific height for the parent, the child element's height can now be calculated as a defined percentage, effectively making percentage height work.
The above is the detailed content of Why Doesn't Percentage Height Work Like Percentage Width in CSS?. For more information, please follow other related articles on the PHP Chinese website!