Sometimes I wish I could do things that were easily done with table-based layouts but quite hard using just CSS.
Update: Error in code solved. Thanks to the testers.
We’re going to write a three-column plus footer layout that covers all the browser space. The requisites are the following:
- The three columns will have different background colors
- We’re not going to use background images (so, no faux-columns)
- We want the page to cover the full height of the browser. So, the footer will be at the bottom of the screen.
- All the code has to be valid and accesible
The first part is simple. We need some html that defines three columns and a footer. Lets wrap the three columns within a div (called, by the way, container) and call the three columns col1, col2 and col3. The html code will be something like:
We need to give the columns a width and float them to the left. The css would be:
So, we already have a three column layout, but each column has a diferent height and the footer is far from the bottom:
Negative margins to the rescue
As I already told you, I had’t heard about creating layouts using negative margins (I should have read this article from A List Apart some time ago). In a nutshell, it says that you can use a large negative margin and the opposite positive padding to “make room for the columns”. I recommend to read it if you haven’t, it’s very useful.
So, let’s go on the code. We’re going to add a -5000 pixel margin-bottom and a 5000 pixel padding-bottom to each column:
This way we get same height columns. This looks much better:
This function returns the height of the browser window. It does one thing and does it well… Using this new knokledge, we can set the height of the columns, making them the browser’s window height minus the footer, to fill the screen completely. The other function we’ll need is:
This function works by calling the last one (windowHeight) and substracting the footer size. If we’re in Explorer, we use style.height to modify the height of the columns and in all other browsers, minHeight, since Explorer doesn’t support that attribute. We’re going to call that function via onload.
And we get this:
If the window is not tall enough to fit the column height, the page behaves normally:
The full code
Putting all together, this is what we get: