Equal Height Columns with jQuery

by Vincy. Last modified on July 12th, 2022.

In a multi-column template, the columns height is based on the content length. If the content lengths are varied then the columns will not be even and will not have a good look and feel. We can do this dynamically to equate the column heights.

We have an example of a two-column template. These two columns have contents with different length. We are going to make these columns with equal height by using jQuery.

View Demo

Two Column HTML Template

This HTML code shows the two column with uneven height.

jquery-equal-height-columns

<header class="cover-box">Header</header>
<div id="outer-div">
	<div id="inner-div">
		<p>Matching main content height to sidebar height...</p>
		<H1 style="padding:100px 0px;">Equal Height Two Column Template</H1>		
	</div>
	<div id="menu-div">
		<p>Matching sidebar height to main content...</p>
		<img src="equal-height.jpg">
	</div>
</div>
<footer class="cover-box">Footer</footer>

and the styles are,

<style>
#outer-div{
	width:778px;
}
#inner-div{    
	background: rgba(199, 230, 175, 0.17);
	display: inline-block;
	width: 57%;
	padding: 10px;
	border: 1px solid #D1DCDA;
}
#menu-div{
	background: rgba(138, 210, 190, 0.45);
	float: right;
	width: 37%;
	padding: 10;
	border: 1px solid #D0D8D1;
}
.cover-box{
	padding: 30px 0;
	border: #D6D2D2 1px dashed;
	margin: 15px 0px;
	width: 778px;
	text-align: center;
	background: rgba(241, 229, 213, 0.25);
}
</style>

Making Equal Height Columns in jQuery

This jQuery script will compare the main and side content heights and take the greater height. Then it will match another column to this height./p>

<script>
$(document).ready(function(){
 	var common_height = 0;
	var content = $("#inner-div");
	var sidecontent = $("#menu-div");
	if($(content).height() >= $(sidecontent).height()) {
		common_height = $(content).height()
	} else {
		common_height = $(sidecontent).height()
	}
	$('#inner-div').css( 'min-height', common_height );
	$('#menu-div').css( 'min-height', common_height );
});
</script>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page