when 100% isn’t enough

The most basic thing you can imagine in a standard web page is a container element, inside which you’d place your page sections.

So, the first thing you’d do is to create something like a DIV container. To test its dimensions you may add a 1px border to it. 

Since the DIV is a block element by default, it will stretch through the page’s width. You will notice your border as a thin line stretched across the screen.

At this point you may be surprised it doesn’t have any height, but on the other hand maybe it shouldn’t. It doesn’t contain anything. That’s fine, but you’d still want it to cover the screen and not stretch according to its content.

Your width is fine, so just add height: 100% and you’re good to go.

Well, it appears that somehow the document’s BODY tag doesn’t have any height either. Right click the page and inspect the body. Surprisingly it doesn’t. 

So, the next logical step would be to set the BODY’s height to 100%.

Inspect the HTML tag. It also has a height of zero.

Wait a minute! This can’t be THAT complicated. We just wanted to cover the page. What happened?

Point the inspector to the HTML tag. Well, wouldn’t you believe it, it’s also a block element! This means that it also doesn’t have any intrinsic value.

Here’s the deal: the topmost tag is not the first element in the chain. The viewport is! Although it doesn’t appear in the DOM, it’s there behind the scenes. So the secret key here is to set the HTML’s height to 100% as well! Every element in the chain has to have some sort of value, be it explicit or implicit. In our case we want to cover the viewport, so all of the elements must chain that 100% all the way down to the container DIV.

Of course there are all kinds of solutions to this problem besides this one. The morale of the story is not THE solution, but understanding the root cause.

See, there are all kinds of oddities with CSS and they cause a lot of frustration, but this issue does make sense once you understand the logic behind it. Never underestimate the fundamentals!


Leave a Reply

Your email address will not be published. Required fields are marked *