A common problem when designing for the web is how to create equal height columns. The usual solution is to either resort to JavaScript or CSS absolute positioning, here I will show you how to create equal height columns with pure CSS using the margin
, padding
and float
properties.
HTML
The HTML of our page is going to look something like this:
<div id="wrapper">
<div id="content">
...
</div>
<div id="sidebar">
...
</div>
</div>
CSS
Our page is going to be 500px wide, with a 300px content area and a 200px sidebar. The CSS:
#wrapper {
margin: 0 auto; /* Center the wrapper horizontally */
overflow: hidden;
width: 500px;
}
#content, #sidebar {
margin-bottom: -10000px;
padding-bottom: 100000px;
}
#content {
float: right;
width: 300px;
}
#sidebar {
float: left;
width: 200px;
}
The Demo
Putting this together you end up with something like this:
Why does this work?
The key to creating equal height columns using this method are the overflow: hidden
selector on the wrapper and the large padding-bottom
and negative margin-bottom
. Any padding is hidden when setting the overflow of the container to hidden. Basically, this means that by setting a large enough padding-bottom
then we can effectively stretch the background colour of the element to the bottom of the page. If 10000px isn’t enough then just make it even larger.
The large negative margin-bottom
then tells the browser where to render the bottom of the box (I think. Don’t quote me on that). If we had set a height
of the container this wouldn’t have worked, and without the negative margin-bottom
we would have ended up with a container over 10000px tall.
When using this method always make sure that you set the margin-bottom
to be equal and negative of the padding-bottom
.
And the best bit of this method? If you decide that you now want your sidebar on the right, simply set float: right
on the #sidebar
and float: left
on the #content
.
Comments