Equal height columns
There are many solutions out there regarding this old problem, of course, some better than others, and I had to try a come up with my own way of doing this. My question was how to set the height property of a div 100% of the container, which had the height set to auto. This could be used for the initial problem.
If we use Javascript, this can be very easily achieved.
First, let’s take a look at the mark-up:
<div id="container"> <div id="column1"> ... </div> <div id="column2"> ... </div> </div>
A standard container, with two child <div>’s. Now for the CSS:
#container
{
width:402px;
height:auto;
overflow:auto;
border:1px solid red;
}
#column1
{
width:200px;
height:auto;
float:left;
background-color:#00CC99;
}
#column2
{
width:200px;
height:auto;
float:left;
background-color:#0066FF;
}
Finally, we add a small script, just before the </body> tag:
<script language="javascript">
div1 = document.getElementById('column1');
div2 = document.getElementById('column2');
if(div1.offsetHeight > div2.offsetHeight)
div2.style.height = div1.offsetHeight + 'px';
else
div1.style.height = div2.offsetHeight + 'px';
</script>
The basic idea is to just set the height property of the smaller <div> equal to the taller one. Ok, that might not be the ultimate solution to this problem but it works if you need a quick way of rendering columns of equal height and you don’t want to use Faux columns.
You can see this little demo here.
I tried to use the javascript code inside the head tag and it didn’t work. But when I used it just before the end body tag it worked. And I was wondering why?
Can it be because you must first have the browser display the content inside the columns and figure out the height and just after that you can change the actual height of it?
It’s just a simple curiosity …
Hello Pavel. I forgot to mention why we actually need to insert the Javascript code at the end.
In order to manipulate DOM elements, you need to have them rendered. But you were right as well. For this script, we need to have the content set so that the height of the elements can be determined, evaluated and then modified (if necessary).
This is a pretty nifty little trick. It saves time then finding other approaches to the same solution.