Javascript Abuse #2,463,981: Centering Content

Another quick rant/post about the wonderful world of abusing javascript. Consider the following code:

function moveScreen() {
    var myWidth = 0,
    myHeight = 0;
    if (typeof(window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && 
		(document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
 
    var marginLeft = Math.max(0, Math.floor((myWidth - 995) / 2));
    $("screen").style.marginLeft = marginLeft;
    $("sidebarElements").style.left = marginLeft + 10;
}
 
Event.observe(window, "resize",
    function() {
        moveScreen()
    });

For the love of all that is good and pure, if you ever find yourself writing something like this just calm down, take a deep breath, and remind yourself that you can accomplish the same thing by:

  1. Create for your content a parent all-encompassing container div, with an id like “parentContainer”
  2. In your stylesheet,
    #parentContainer {
    	width: 955px;
    	margin: 0 auto;
    }

That is all, keep on truckin’.

Recent Entries

Comments are closed.