fixing css columns
2007-10-25 @ 18:52#
lots of ways to do this. since i'm a coding geek, i use javascript to even out columns in a CSS display. typically, i use a container
element to hold the layout. not purist, but functional. below is a simple three-column CSS fixed-width layout with varying height columns. there's a single javascript method attached to the window.onload
event that scans for special CSS classes and uses them to adjust the column heights on the fly. i set the background-color
of the element to make it easy to see how things work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Three-Column Adjusted</title> <style type="text/css"> /* * NOTE: * subtract any added padding/border from the total width of the element. * To add a background to the container, add a clearing element after the columns. */ body { margin:0px; padding:0px; } #container { width: 1000px; margin: auto; } #leftbar { text-align:left; float: left; width: 200px; background-color:green; } #content { text-align:left; float: left; width: 600px; background-color:yellow; } #rightbar { text-align:left; float: right; width: 200px; background-color:silver; } #header { text-align:left; background-color:red; } #footer { text-align:left; clear: both; background-color:red; } </style> <script type="text/javascript"> var fixColumns = { containerCSS : 'fx-container', columnCSS : 'fx-column', headerCSS : 'fx-header', footerCSS : 'fx-footer', init:function () { var divs = document.getElementsByTagName('div'); for(var i=0;i<divs.length;i++) { if(divs[i].className.indexOf(fixColumns.containerCSS)!=-1) { var height = divs[i].offsetHeight; var coll = divs[i].getElementsByTagName('div'); for(var j=0;j<coll.length;j++) { if(coll[j].className.indexOf(fixColumns.headerCSS)!=-1) { height=height-coll[j].offsetHeight; } if(coll[j].className.indexOf(fixColumns.footerCSS)!=-1) { height=height-coll[j].offsetHeight; } } for(var j=0;j<coll.length;j++) { if(coll[j].className.indexOf(fixColumns.columnCSS)!=-1) { coll[j].style.height = height+'px'; } } } } } } window.onload = fixColumns.init; </script> </head> <body> <div id="container" class="fx-container"> <div id="header" class="fx-header"> HEADER </div> <div id="leftbar" class="fx-column"> LEFT<br /> LEFT<br /> LEFT<br /> LEFT<br /> LEFT<br /> </div> <div id="content" class="fx-column"> CONTENT<br /> CONTENT<br /> </div> <div id="rightbar" class="fx-column"> RIGHT<br /> RIGHT<br /> RIGHT<br /> RIGHT<br /> RIGHT<br /> RIGHT<br /> RIGHT<br /> </div> <div id="footer" class="fx-footer"> FOOTER </div> </div> </body> </html>