Coding with Jesse

Resizing a web layout based on browser size

May 19th, 2007

Some people thought that my new layout was too thin, and I had to agree. Originally, I wanted the width of the text on the page to be in a more narrow, more readable column. I also tried to stick to a layout that could fit within a browser on an 800x600 resolution. The result was a column of text that was less readable because it was too narrow.

Today, I added a bit of JavaScript to the page to resize the layout for anyone with a browser wider than 930px. The JavaScript looks like this:

var body_check = setInterval(function(){
    if (document.body) {
        clearTimeout(body_check);

        if (document.body.clientWidth > 930)
            document.body.className += ' wide';
    }
}, 10);

Every 10ms, this script checks if the body is available yet. As soon as it is, the checking is cancelled, and the 'wide' class is added to the body if the browser is wider than 930px.

I opted for a polling technique instead of using window.onload, or even instead of addDOMLoadEvent, so the design wouldn't noticeably jump when the class was added.

To go along with this JavaScript, I added the following in the CSS:

#body { width: 760px; }
#main h1 { width: 560px; }
#main .section { width: 444px; }

body.wide #body { width: 910px; }
body.wide #main h1 { width: 710px; }
body.wide #main .section { width: 594px; }

I isolated the 3 fixed widths that would need to change, and simply increase each of them by 150px whenever the 'wide' class is added to the body.

I hope this wider design is a bit more readable for the 98% of you with a higher resolution.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!