P粉7594512552023-08-21 18:49:34
You also need to set the height on the <html>
and <body>
elements; otherwise, they will only be large enough to fit the content. For example:
<!DOCTYPE html> <title>Example of 100% width and height</title> <style> html, body { height: 100%; margin: 0; } div { height: 100%; width: 100%; background: red; } </style> <div></div>
P粉5305192342023-08-21 00:27:22
What is the percentage?
To set the percentage height, its parent element (*) must have an explicit height. This is fairly obvious, if you leave the height as auto
, the block will take the height of its content... However, if the height of the content itself is expressed as a percentage of the parent element, you're stuck in a Little dilemma. The browser gives up and just uses the content height.
Therefore, the parent element of the div must have an explicit height
attribute. While the height can be a percentage if you prefer, that just takes the problem to the next level.
If you want the height of a div to be a percentage of the viewport height, then every ancestor element of the div, including <html>
and <body>
, Must have height: 100%
, so there is an explicit percentage height chained to the div.
(*: Or, if the div is positioned, the "containing block", the nearest ancestor element that is also positioned.)
Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh
) and viewport width (vw
):
div { height:100vh; }
View hereMore information.