body{height:100%}
and html, body {height:100%}
have a crucial difference related to how the browser calculates the height of the body
element. The html
element represents the root of the document, while the body
element contains the visible content.
Here's the breakdown:
-
body { height: 100% }
: This sets thebody
's height to 100% of its parent's height. If the parent (html
) doesn't have an explicitly defined height, thebody
will not take up the full viewport height. It might only be as tall as its content. This is because thehtml
element, by default, doesn't necessarily have a height of 100% of the viewport. -
html, body { height: 100% }
: This sets both thehtml
andbody
elements to 100% height. Crucially, setting thehtml
element's height to 100% makes it fill the entire viewport height. Then, thebody
, having its height set to 100% of its parent (html
), will also fill the entire viewport height. This is the key to making the body occupy the full browser window.
To your question, "Isn't html
the entire window already?", the answer is subtly no. The html
element contains the entire window's content, but its height isn't automatically the viewport height unless explicitly set. It adjusts to the content within it unless told otherwise.
Why is this important?
This is crucial for layouts where you want elements within the body
to have percentage-based heights. If the body
doesn't have a defined height relative to the viewport, percentage heights for child elements won't work as expected. They'll be calculated relative to the body
's height, which might be smaller than the viewport.
In summary:
To ensure the body
element takes up the full viewport height, you must set both the html
and body
elements' height to 100%. Setting only the body
's height to 100% is insufficient if the html
element's height isn't also explicitly set.