SunQuest
 
       Web Standards
  Home arrow Web Standards arrow Page 4 - Matching div heights with CSS and JavaScri...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
WEB STANDARDS

Matching div heights with CSS and JavaScript
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 34
    2005-03-14

    Table of Contents:
  • Matching div heights with CSS and JavaScript
  • The kingdom of non-matching heights
  • More non-matching heights just around the corner
  • The JavaScript solution

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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.

       ·  I think that the exposed technique is easy to understand and effective to maintain...
       · The idea of javascript is good, but it's just working with IE only. I didn't play...
       ·  Hello friend, The solution works in IE, Netscape 6+ and Mozilla. So, It might...
       · I have only been able to get the script working in IE 6. Been having a mess about...
       · I don't understand why a web developer would do this. If a web surfer has...
       · Hello again,The script works fine in Firefox and Netscape 6+. I've tried it, and...
       · Yes, what you're pointing is correct. It's another possibility to achieve the same...
       · Modern browsers, like FireFox 1.0+ (and I'm guessing Netscape 6+) support CSS2.1,...
       ·  Well, I think that display: table-cell could be pretty easily to be implementedon...
       · Am I the only one that thinks it is crazy that we are running around coming up with...
       · Your opinion it truly worthy, since the use of tables is currently strong. The...
       · Actually it doesn't work in firefox. To get it working, you need to add 'px' to the...
       · The addition of the 'px' unit is recommendable. However, I've tested the script in...
       · I've tried this over and over and over again on my three column absolutely...
       · The script works great in IE, Firefox and Opera. However, I had a problem with the...
       · Thank you for your feedback here. In fact, the problem you mention shouldn't be that...
       · I was struggling with this - I could get it to work in html but not xhtml, and then...
       · I meant "http-equiv" meta tag - apologies.
       · Hello,Thank you for your introducing your comments on my article. Also, I'm glad...
       · No problem at all, friend. I understood what you meant.Thank you.
       · The script does exactly what it is supposed to do (thanks by the way for the...
       · Thank you for your detailed feedkack on my article, and particularly about your...
       · This seems unnecessarily complicated. This effect (as mentioned before) can be...
       · Hello Martin,Thank you for commenting in this article. Although the script is...
       · Alejandro, any way to have this great JS code working also on HXTML? Please let me...
       · First off, thank you for commenting here. Now, concerning your question, if you're...
       · I've looked at about 50 tutes for a pure CSS solution to this problem as I agree...
       · First of all, thank you for commenting here. Now, concerning the DIVS issue, if...
     

    WEB STANDARDS ARTICLES

    - 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







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway