CSS Height Percentage Not Functioning
When attempting to specify an element's height as a percentage, it may fail to display as expected. This is because the percentage height is relative to its parent element. Therefore, it is crucial to set the height of all parent elements to 100%.
In the provided code snippet:
<div>
The issue arises from the absence of a height declaration for the parent elements, namely the body and html elements. Without this declaration, the percentage height for the div is interpreted relative to its parent's default height, which is typically not set.
To resolve this issue, explicitly set the height of both the body and html elements to 100%, ensuring that they occupy the entire viewport:
html, body { height: 100%; width: 100%; margin: 0; }
By setting the html and body elements to 100% height, the div element is now able to correctly calculate its height based on its parent's height, which is now 100% of the viewport. As a result, the div will correctly display with its height spanning the entire height of the browser window.
The above is the detailed content of Why Doesn't My CSS Percentage Height Work?. For more information, please follow other related articles on the PHP Chinese website!