Typically, when you want to have html
and body
take on the height of the viewport but also allow them to expand with the content, you set height: 100%
on html
only, and min-height: 100%
instead of height
on body
. Further explanation can be found in my answers to the following questions:
Unfortunately, because html
is the root element, you cannot set min-height
on it alone, or everything will fall apart. You need height: 100%
because otherwise there is no parent height on which to base body
and its contents; the height of html
itself is based on the height of the viewport, which as you may have guessed is pre-determined.
This will be problematic if your actual layout has borders on all these elements, so instead I'm going to assume the borders aren't actually needed. You do not need to worry about the background because it will automatically be transferred to the viewport allowing it to cover the entire painting area (details in the second link).
Given your CSS, you can simply set height: auto
on body
to cancel out the height: 100%
in your previous rule, along with min-height: 100%
:
html, body, div {
background: rgba(0, 0, 0, .2);
margin: 0;
padding: 20px;
height: 100%;
}
body {
height: auto;
min-height: 100%;
}
Note that I've also removed the borders, again based on my assumption that they're not needed.
Now we have another problem: once the content grows beyond the browser height, the padding on html
disappears, since html
doesn't expand along with the other content due to height: 100%
(scroll to the bottom to see this).
You can't remove height: 100%
since it's required, but you can still change the padding on html
to margins around body
instead because the margins will continue to take effect even once body
overflows html
, resulting in the following (again, scroll to the bottom):
html, body, div {
background: rgba(0, 0, 0, .2);
margin: 0;
padding: 20px;
height: 100%;
}
html {
padding: 0;
}
body {
height: auto;
min-height: 100%;
margin: 20px;
}