Home arrow Web Standards arrow Page 4 - Matching div heights with CSS and JavaScript
WEB STANDARDS

Matching div heights with CSS and JavaScript


It's not unusual for the layout of a Web page to feature multiple columns. Unfortunately, when creating this layout while using general <div> containers, you can end up with columns of uneven height, depending on their content. This looks very unprofessional. Alejandro Gervasio explains a way to keep your column heights even using CSS and JavaScript.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 60
March 14, 2005
TABLE OF CONTENTS:
  1. · Matching div heights with CSS and JavaScript
  2. · The kingdom of non-matching heights
  3. · More non-matching heights just around the corner
  4. · The JavaScript solution

print this article
SEARCH DEVARTICLES

Matching div heights with CSS and JavaScript - The JavaScript solution
(Page 4 of 4 )

Since originally we defined three columns for page layout, the solution will be developed while sticking to the initial example. However, due to the portability of JavaScript code, it is perfectly applicable to any number of columns which we want to be efficiently matched. Our CSS code closely matches the previous examples, and is listed here:

<style type="text/css">

body {

     margin: 0px;

}

#leftcol {

     float: left;

     width: 17%;

}

#content {

     width: 65%;

     float: left;

}

#rightcol {

     float: right;

     width: 17%;

}

.container {

     background: #ccf;

     border: 1px solid #000;

}

</style>

As you can see, we've defined the three <div> main columns originally presented, and an additional "container" class that will be used to hook up a style for each column, if we really wish to do it. In the example, I've chosen to give a background color and borders. However, this is not mandatory at all. Also, the "container" class will provide us with an easy way to identify the columns to be targeted by the script within the markup.

The HTML markup is nearly identical to the previous examples. We just added the "container" class to each <div> element susceptible to being affected by the JavaScript function. Here's the code:

<div id="leftcol" class="container">

Left Section<br /><br />

Content goes here...

</div>

<div id="rightcol" class="container">

Right Section<br /><br />

Content goes here...

</div>

<div id="content" class="container">

Content Section<br /><br />

Content goes here...<br />

Content goes here...<br />

Content goes here...<br />

Content goes here...<br />

Content goes here...<br />

Content goes here...

</div>

Nothing unexpected, is it? Finally, we list the JavaScript code, necessary to perform column height matching. It is as follows:

<script language="javascript">

matchHeight=function(){

     var divs,contDivs,maxHeight,divHeight,d;

     // get all <div> elements in the document

     divs=document.getElementsByTagName('div');

     contDivs=[];

     // initialize maximum height value

     maxHeight=0;

     // iterate over all <div> elements in the document

     for(var i=0;i<divs.length;i++){

          // make collection with <div> elements with class attribute 'container'

          if(/\bcontainer\b/.test(divs[i].className)){

                d=divs[i];

                contDivs[contDivs.length]=d;

                // determine height for <div> element

                if(d.offsetHeight){

                     divHeight=d.offsetHeight;

                }

                else if(d.style.pixelHeight){

                     divHeight=d.style.pixelHeight;

                }

                // calculate maximum height

                maxHeight=Math.max(maxHeight,divHeight);

          }

     }

     // assign maximum height value to all of container <div> elements

     for(var i=0;i<contDivs.length;i++){

          contDivs[i].style.height=maxHeight;

     }

}

// execute function when page loads

window.onload=function(){

     if(document.getElementsByTagName){

          matchHeight();

     }

}

</script>

As we usually do, let's break down the code to give a detailed explanation about each section of it:

At first, the function obtains the <div> elements present in the document. The line

divs=document.getElementsByTagName('div');

takes care of that.

Then, the script initializes the array structure for storing all of the <div> elements with class attribute set to "container," followed by the initialization of the variable "maxHeight," which will store the maximum height value found for the divs targeted. Next, the function traverses all of the <div> elements and checks for those with class attribute set to "container." These elements are stored in the array "contDivs" for further processing. The lines below perform that task:

if(/\bcontainer\b/.test(divs[i].className)){

                d=divs[i];

                contDivs[contDivs.length]=d;

---

}

Now, let's explain the key section of the script. For each targeted <div> element, we need to calculate its height, in order to determine which <div> has the greatest height value. To do that, we're using alternatively  the offsetHeight and pixelHeight properties in order to determine the height value expressed in pixels for an element. This snippet performs the above mentioned process:

if(d.offsetHeight){

divHeight=d.offsetHeight;

}

else if(d.style.pixelHeight){

     divHeight=d.style.pixelHeight;

}

Finally, the code determines the greatest <div> height of all of the elements analyzed, with the following expression:

maxHeight=Math.max(maxHeight,divHeight);

Once the function has determined the greatest height value of all the <div> elements, the only thing left to do is assign that value to each container <div> height, performing the needed matching for <div> height values. The last thing to do is wrap the whole code into a JavaScript function that will be executed when the page finishes loading. After the execution of the script, the visual output for the example might look similar to this:

Definitively, that looks a lot better than the previous cases, don't you agree? We've implemented height matching with the columns present in the Web page. That's pretty good! 

Summary

In this article we've shown the specific problem of non-matching heights when working with <div> based layout, and hopefully demonstrated a very simple and portable solution. One worthy suggestion about this approach is that if we have a footer section in the page, as is commonly present on most websites, it'd be convenient to initially hide it from view, and once the height matching process have been completed with columns, turn it visible again. After all, those divs are not so wild as they seem to be!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
WEB STANDARDS ARTICLES

- Mozilla Popcorn Maker 1.0 Makes Videos More...
- Completing a Configuration for Chrome and a ...
- Getting Connected with Firefox and Chrome
- Configuring Servers and Databases with Chrome
- Configuring Firefox for Chrome and a Server
- Designing the Elements of a Web Page
- Matching div heights with CSS and JavaScript
- Forms
- Get Down With Markup
- If I Said You Had a Beautiful Body...
- Web Standards in Dreamweaver Part 3
- Web Standards in Dreamweaver, Part 2
- Web Forms
- Making Lists Using XHTML
- Web Standards in Dreamweaver, Part 1

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials