• Resizing a web layout based on browser size

    May 19 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) {
            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.

  • Comments

    1. Mauvis at 9:41pm on May 20, 2007

    I dig it. I disabled JavaScript and I can see what you mean about it being a little too narrow (I'm 1280x1024.)

    Yay for progressive enhancement.

    2. Nick at 1:09pm on August 8, 2007

    awesome script
    how could you resize an image as well?

    3. Kristine at 10:30pm on March 21, 2008

    surely there's a way to make it work the other way around - resizing it for everyone *under* 930px? if there is a way, PLEASE could you let me know? that would save my final project!!!

    4. Jesse Skinner at 10:28am on March 23, 2008

    @Kristine - that's simple. Just change the example above to check for a width less than 930:

        if (document.body.clientWidth < 930) {
            document.body.className += ' thin';

    5. Mohammed Jaffer at 1:22pm on December 9, 2011

    hi jesse,

    im working in a company as a web-designer. last week ive got  a project. in which i have to make webpage resize according to the browser resolution.do you have any idea ? please help.


    Commenting is now closed. Come find me on Twitter.