CSS Trick: How to get the height 100%

CSS height 100% working

This is a fairly simple trick, yet many designers are unaware of why when you set an element’s height to 100% it just doesn’t work, or how to fix that.

The thing is, your element is just as tall as it’s parent is, so if it’s parent’s height is not set, or set to auto, both elements will have the height of the content of the child element.

CSS height 100% not working

For example, if you set an element like this:

<html>
<head>
</head>
<body>
<div id="container">I'm a div that just won't stretch to the full height of the page.</div>
</body>
<html>

and the CSS like:

#container {height:100%}

the container div will be as tall as the text inside it, the body and html elements will remain the same height of the container element, since their height attribute is not defined.

What you need to do in order to get the element to the full height of the window is set a height to the HTML and BODY elements. Once they have their height set to 100%, their child elements will be able to adjust to them.

CSS height 100% working

Here’s the full working code if you want to play with it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<style type="text/css">
html, body, #container {height:100%; margin:0; box-sizing:border-box; -moz-box-sizing:border-box;}
#container {vertical-align:middle; text-align:center; background:#0CF; color:#fff; font-size:4em; padding-top:20%}
</style>

</head>

<body>
<div id="container">I'm a div that stretches to the full height (100%) of the page.</div>
</body>
</html>

Sharing is caring!


Leave a Reply

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