Monday, March 9, 2009

Equal height DIV boxes with CSS

Web designers are really like the idea of being able to place two or more containers, or boxes, side by side and make them be of equal height, regardless of how much content is in each box. Web designers also like to vertically centerlized or bottom-align the contents of a container.


Traditionally, all that was needed to achieve that was to make each box a cell in a table row. We don’t want to use tables for layout anymore, however, so we need to find some other way. And that’s where the problems begin. Not because it isn’t possible to use CSS for the above effects, but because Internet Explorer doesn’t support it.


To prove that it’s actually very easy to create equal height columns with CSS, I’ve made and attached with sample demo, consisting of three boxes that are displayed side by side. They all have the same height, and will adjust to the height of whichever box is tallest. The contents of one of the boxes is vertically centered.


The trick is to use the CSS properties display:table, display:table-row and display:table-cell to make containers (in this case div elements) behave like table cells.


The basic XHTML structure looks like this:


<div class="equal">      <div class="row">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div> </div>

Here is the CSS used to make this structure:


.equal {margin:10px auto;border-spacing:10px;background:#ff0000;
width:80%;display:table;border-collapse:separate;

}

.row {display:table-row;}

.row div {background:#fff;display:table-cell;}

.row div.one {width:40%;}

.row div.two {width:40%;}

.row div.three {vertical-align:middle;}

In the demo, I’ve used border-collapse:separate and border-spacing:10px; to add a bit of space between the boxes. This is the equivalent of using the cellspacing attribute.


Like I said, this does not work in Internet Explorer, but it works in all modern browsers I have tested in: Internet Exporer 8.0, Mozilla 1.6, Opera 7.50, Safari 1.2.2, Firefox 0.8, OmniWeb 5b, Camino 0.8b, and Netscape 7.1.

Labels:



1 Comments:

At March 12, 2009 at 1:10 PM , Anonymous Anonymous said...

Just by surfing around in net I definitely found a very informal place with a lot of good stuff for everybody. I will certainly visit your site again sometime. Really good work.

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home