While designing layouts I set the html, body
elements' height
to 100%
but in some cases, this fails, so what should be used?
html, body {
height: 100%;
}
or
html, body {
min-height: 100%;
}
Well, this is not opinion based as each method has its own flaws, so what's the recommended way to go for and why?
Conclusion. With no height value provided for the HTML element, setting the height and/or min-height of the body element to 100% results in no height (before you add content). However, with no width value provided for the HTML element, setting the width of the body element to 100% results in full page width.
Try setting the height of the html element to 100% as well. Body looks to its parent (HTML) for how to scale the dynamic property, so the HTML element needs to have its height set as well. However the content of body will probably need to change dynamically. Setting min-height to 100% will accomplish this goal.
The difference between height and min-height is that height defines a value for the height and that's how tall the element will be. min-height says that the minimum height is some value but that the element can continue to grow past that defined height if needed (like the content inside makes it taller or whatever).
You could consider min-height: 100vh; . This sets the height equal or greater to the size of the screen, vh: vertical height .
If you're trying to apply background images to html
and body
that fill up the entire browser window, neither. Use this instead:
html {
height: 100%;
}
body {
min-height: 100%;
}
My reasoning is given here (where I explain holistically how to apply backgrounds in this manner):
Incidentally, the reason why you have to specify
height
andmin-height
tohtml
andbody
respectively is because neither element has any intrinsic height. Both areheight: auto
by default. It is the viewport that has 100% height, soheight: 100%
is taken from the viewport, then applied tobody
as a minimum to allow for scrolling of content.
The first way, using height: 100%
on both, prevents body
from expanding with its contents once they start to grow beyond the viewport height. Technically this doesn't prevent the content from scrolling, but it does cause body
to leave a gap beneath the fold, which is usually undesirable.
The second way, using min-height: 100%
on both, doesn't cause body
to expand to the full height of html
because min-height
with a percentage doesn't work on body
unless html
has an explicit height
.
For the sake of completeness, section 10 of CSS2.1 contains all the details, but it's an extremely convoluted read so you can skip it if you're not interested in anything beyond what I've explained here.
You can use viewport height (vh
) unit:
body {
min-height: 100vh;
}
It is relative to screen, not to parent height, so you don't need html height: 100%.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With