Introduction
This tip shows how to set all columns in a div
container to equal height by a single jQuery function.
Using the Code
First, add the following HTML markup to a web page for testing purposes.
<div class="col-container">
<div class="col col1">
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
</div>
<div class="col col2">
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
</div>
<div class="col col3">
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
This is a sentence to test jQuery column equal height function.
</div>
</div>
Second, add some CSS code for the HTML markup.
.col-container
{
width: 80%;
margin: 0 auto;
}
.col-container:after
{
content: "";
display: block;
clear: both;
}
.col
{
float: left;
width: 33.3%;
}
.col1
{
background-color: #FF0000;
}
.col2
{
background-color: #00FF00;
}
.col3
{
background-color: #0000FF;
}
All columns inside the container are floated to left. CSS :after
selector is used to add an empty content after the container and clear the float. This trick makes subsequent content display normally. Otherwise, the following content may overlap with these columns.
Last, add the jQuery code to set these columns with equal height.
$(document).ready(function () {
var equalHeight = function () {
$('.col').css('height', 'auto');
var maxHeight = 0;
$('.col').each(function () {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$('.col').css('height', maxHeight);
};
equalHeight();
$('.col-container').resize(function () {
equalHeight();
});
});
The function equalHeight
first sets the height of each column to auto
. This allows the browser to automatically calculate its height. Then it iterates through all columns and finds the maximum height. Last, it sets all columns to the maximum height.
All columns inside a div
are set to equal height when the page is loaded and when the div
container is resized.