HTML/CSS: Making two floating divs the same height
I have a little peculiar problem that I currently solve using a table
, see below. Basically, I want to have two divs take up 100% of the available width, but only take up as much vertical space as needed (which isn't really that obvious from the picture). The two should at all times have the exact same height with a little line between them, as shown.
(source: pici.se)
This is all very easy to do using table
, which I'm currently doing. However, I'm not too keen on the solution, as semantically this is not actually a table.
You can get equal height columns in CSS by applying bottom padding of a large amount, bottom negative margin of the same amount and surrounding the columns with a div that has overflow hidden. Vertically centering the text is a little trickier but this should help you on the way.
#container {
overflow: hidden;
width: 100%;
}
#left-col {
float: left;
width: 50%;
background-color: orange;
padding-bottom: 500em;
margin-bottom: -500em;
}
#right-col {
float: left;
width: 50%;
margin-right: -1px; /* Thank you IE */
border-left: 1px solid black;
background-color: red;
padding-bottom: 500em;
margin-bottom: -500em;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head></head>
<body>
<div id="container">
<div id="left-col">
<p>Test content</p>
<p>longer</p>
</div>
<div id="right-col">
<p>Test content</p>
</div>
</div>
</body>
I think it worth mentioning that the previous answer by streetpc has invalid html, the doctype is XHTML and there are single quotes around the attributes. Also worth noting is that you dont need an extra element with clear
on in order to clear the internal floats of the container. If you use overflow hidden this clears the floats in all non-IE browsers and then just adding something to give hasLayout such as width or zoom:1 will cause IE to clear its internal floats.
I have tested this in all modern browsers FF3+ Opera9+ Chrome Safari 3+ and IE6/7/8. It may seem like an ugly trick but it works well and I use it in production a lot.
I hope this helps.
It is year 2012+n, so if you no longer care about IE6/7, display:table
, display:table-row
and display:table-cell
work in all modern browsers:
http://www.456bereastreet.com/archive/200405/equal_height_boxes_with_css/
Update 2016-06-17: If you think time has come for display:flex
, check out Flexbox Froggy.