Grow your CSS skills. Land your dream job.

Different Stylesheets for Differently Sized Browser Windows

Published by Chris Coyier

Otherwise known as "resolution dependent layouts". Single website, different CSS files for rearranging a website to take advantage of the size available.

There is a W3C standard way of declaring them. One way is to test the "device-width", like this:

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />

The above code will apply the 800.css styling to the document only if the device viewing it has a width of 800px or wider. And... supports "media queries" in this way.

Keep in mind this is the device width, not the current width of the browser window. On the iPhone (3G(s)), that means 480px. My fancy new MacBook Pro is going to return 1920px for the device width. But my actual browser window is only half of that at this exact moment. The device width is quite useful when dealing with mobile devices where the browser is probably 100% of the screen whenever in use, but less useful in laptop/desktop browsers.

Seems to me far more useful is the current width of the browser window ("viewport"). We can even specify stylesheets that are only to be used when the viewport is between two different pixel sizes:

<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />

That stylesheet will only take affect when the current browser window is between 701 and 900 pixels in width.

Browser Support

IE 9+, Firefox 3.6+, Safari 3+, Any Chrome, Opera 10+. Mozilla suggests starting the media attribute of the <link /> with "only" which will hide the stylesheet from older browsers that don't support media queries. That may or may not be what you actually want to do... case dependent of course.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

Generally, layout is one of those things that it's tough to sell "progressive enhancement" on. Rounded corners becoming squares, no big deal. Messed up layout, that is a big deal. Devices like the iPhone right now are kind of great, since browser choice is so limited (there used to be just Mobile Safari and that's it, now there is Opera as well) and they are very good browsers, you can rely on techniques like this to work.

If IE support is paramount, we always have JavaScript!

Doing it with jQuery

Using JavaScript, we can test the windows width and change the active CSS file accordingly. This will work across all browsers. You can have an ID for a <link /> element like any other, so let's add that:

<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />

Then we can use that as a hook and change the href value of the stylesheet. The browser will see that change and unapply the old CSS and reapply the newly linked CSS. We'll run our little adjustment test once right away, and then anytime the window is resized thereafter.

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

Is jQuery really necessary just for this?

No, but I'm sure you know that's just how I roll in general and it makes it easier. Kevin Hale wrote about dynamic resolution layouts literally five years ago. It's "raw" JavaScript and still works great today.

Also, there is a kick ass polyfill: Respond.js

Video

Example One

This one has a special stylesheet for narrow (less than 700px), medium (701 - 900px), and wide (greater than 901px) browser windows.

View Demo

Example Two

This does the exact same thing as example one, only through jQuery/JavaScript instead of CSS media queries.

View Demo

Example Three

This example shows that we can target mobile devices by testing for a maximum device width.

View Demo

Download

Snag all of these for reference in one place.

Download Files

Comments

  1. PJ
    Permalink to comment#

    This is awesome. Many thx.

  2. Looking to the future, will web designers have start making sites that are some the biggest & smallest to accomodate? Ask that question. :-P

  3. Bowe Frankema
    Permalink to comment#

    Nice! Thanks for this Chris :)

  4. Spreng
    Permalink to comment#

    Great tip! I’m going to give this a try. Thanks!

  5. Very cool! Reminds me of http://lessframework.com/

  6. interesting note: DreamweaverCS5 in all it’s wysiwyg glory supports this functionality….not the jquery bit, though. I saw a video of it when I was geeking out on all the cs5 previews.

  7. Great article! Thanks for the walk-through.

  8. Dan P
    Permalink to comment#

    ITS OVER NINE HUNDREEEDDD!!!

    lol, had to.

  9. Daniel
    Permalink to comment#

    Wow, this is just great!

  10. Dim
    Permalink to comment#

    Lovely… what aboute Opera?

  11. Permalink to comment#

    Wow, this comes in handy! Thanks!

  12. Awesome! I was looking for this.

  13. Awesome idea and awesome examples Chris, but as much I like it, it also scares me. In the wrong hands, will the power be used for good or evil?

  14. Permalink to comment#

    Great article..

    Thanks chris..

  15. Permalink to comment#

    Great job. Love the workaround for IE. (Even though I don’t use it)

  16. I wrote a jQuery plugin for this, so it is interoperable between browsers (even the IE family): jQuery browserSizr.

    http://www.csslab.cl/2009/07/22/jquery-browsersizr/

  17. Great article thanks.

  18. kn33ch41
    Permalink to comment#

    You don’t need JavaScript to build fluid layouts. Sure, it’s cool to display additional content, but if you don’t have it there initially, you might as well just stick to what you have. Make all your site fluid and you have this effect too.

    • Terry Willard
      Permalink to comment#

      This is not a strict fluid layout though. It is a completely different layout depending on the window width.

      A true fluid layout would just scale widths measured in percent.

  19. Time Roll
    Permalink to comment#

    Nice one, thanks!

    Btw, what is the name of the iphone simulator?

  20. Carlos
    Permalink to comment#

    I am loving the alternate CSS sheets with max width. That takes care of a lot of things I am working on for Mobile devices without using jQuery if the browser does not have javascript support.

  21. Carlos
    Permalink to comment#

    Does the max device width work on IE browser devices? Blackberries, Androids, I know iPhones for sure.
    Or is javascript the way to go on those. I hate developing for IE or any device using IE but it must be done. I don’t think many IE mobile devices even have Javascript enabled on their browsers. Don’t know about the Mobile7 MS devices.
    Very cool article.
    thanks in advace.

  22. Would this work with @media?
    Ex.
    @media screen and (min-width: 490px) and (max-width: 1600px) {
    }

    • Permalink to comment#

      Yes, that is how I like doing it!

      You have many options for specifying Media Queries, but I have to admit, this seems neatest to me.

  23. This is AWESOME!!! Thank you sooo very much for sharing. I could have used this a long time ago. : )

  24. I would like to see a liquid-layout version of this where each of the three layouts stretched to fill the full width of the browser viewport. Then it would truly be a resolution independent layout.

    Nice article Chris.

  25. I tried the media=”only screen and (color)” with IE 9 Platform Preview and it doesn’t support it so far.

    Interesting article, Chris. I think it would be cool to use this to increase the main-content area’s width for people with larger screens.

  26. Just a FYI: You call it Vanilla, not “raw” JavaScript.

  27. Great tip. This probably is more dificult to implement but it gives me that warm felling that it’s the right way to do it. Designing sites that run anywhere beautifully. :)

    Any thoughts about the best way to implement this on a layout with images? Probably it would envolve using some of the techniques described by robot ninja at http://unstoppablerobotninja.com/entry/fluid-images/

  28. Great info !!! Thanks for sharing Chris

  29. I knew how to do this with javascript but not “device-width” thing. It is very cool~

  30. Marco
    Permalink to comment#

    Very nice, I was just looking for a clean way to target mobile devices.

    One thing though: the second example doesn’t work right in Chrome on Windows; the Content and Extra div’s aren’t aligned properly. Is this because of the demoing or is this something with the JS? (as far as I can see it uses the same stylesheet).

  31. Gregory Hernandez
    Permalink to comment#

    cool for designers/developers. but, will readers find shifting/moving content useful?

  32. esther
    Permalink to comment#

    wow! thanks!
    Was working on something like this . it helped

  33. Ok that’s awsome! Endless possibilities.

    You kinda cut it short to the end, what happened? :)

  34. After reading this it has made me really think whether I should start designing sites so that they are iPhone etc friendly.

    I look at the sites have done in iPhones and other portable media devices, and they look fine, only issue is scrolling sideways etc. But I guess the future seems to be heading towards small screen devices and therefore sites should cater for the growing market.

    I have read somewhere that dreamweaver CS5 will have some kind of functionality that allows you to create a site then dreamweaver will create stylesheets automatically for devices such as iPhones etc.

  35. This and more can be done easily with Elastic CSS Framework, check out Adaptive Columns in the Demo Section.

  36. Ahmed
    Permalink to comment#

    Pretty neat, I didn’t know such thing was possible with pure css–of course IE has to come and ruin it as usual, but thanks for the jQ example too. I wonder you could post a MooTools example too, or maybe this is something to poke David Walsh about xD

  37. I see this feature in Nettut+ blog and would like to make some script to do this. But you’ve already done all of this, even better with only css. Thank you for sharing.

  38. Permalink to comment#

    I totally agree for this method, particularly for development of different stylesheets for various mobile devices.

    Check out ProtoFluid which takes advantage of this technique (we very recently launched it!). http://protofluid.com

    It lets you test CSS3 Media Queries at specified resolutions (i.e. mobile phone widths) with great ease.

    Thanks for the article, great timing ;)

  39. Thanks for useful article. best regards man

  40. Permalink to comment#

    This is nice article….i have come to know first time about define different CSS in header to control layout as per devices.

    I was in habit of using single CSS with 100% width define and when i use %, it automatic adjust as per the browser width.

    Jquery is good and will try that also

  41. kara
    Permalink to comment#

    hi,

    This will be really nice if this will supoort for IE!

    However great technique and thankx for sharing.

  42. Excellent article. Thanks Ted

  43. Maybe you’ll like the auto-resize features of our little jQuery experiment: http://centratissimo.musings.it
    Take a look and let us know if you like it!

  44. Permalink to comment#

    Article comes up on the 23rd, need for exactly this comes up on the 27th. You just saved me from a huge headache. Thankyou!

  45. Martin
    Permalink to comment#

    Really nice article Chris! This could be a nifty trick to support all phones out there. But I’m abit suspicious about it. I mean they dont support jQuerry right?

  46. Permalink to comment#

    A great concept, but I do not feel as though its plausible. Shifting content dependent upon browser width could be exceptionally dangerous. Users do not like when things start shifting about randomly. They have this tendency to think, “What’s going on with this site? Its obviously broken. I’ll go somewhere else.”

    The utilization of device width however, especially for mobile devices, I think is much more useful. Unless you have an already well established web presence or a very tech savvy user base however, I would stay away from the media width.

  47. harinder singh
    Permalink to comment#

    Great Man! Awesome ………………………..

  48. Nice Idea, but I think it don’t work in practice. The reason is for example, images have to be resized for different sizes. If you use it for a mobile design, you maybee load content which isn’t displayed in the end.

  49. I guess this could also be used to, for example, switch layouts when viewing on an iPhone and changing the rotation (portrait/landscape) :)

  50. Ive been looking for a post on this for ages… My friend said you could have different style sheets in a W3C standard way and here it is. Cheers for the resource much appreciated.

  51. Ant

    I want to seel some popular site will adapt @media via css.

    Nettuts+ — only real site I know that using technique, — with javascript.

    I used @media query on some random small project, because was bored (and also to try it out).

  52. Hi,

    I have big problem
    i using width 1180px for layout
    in stylesheet i put container width 1180px;
    in desktop pc my layout no problem but

  53. is it possible to have one main css file, which includes the stylesheets for the relevant resolutions, instead of 3 link tags in the html?

    greatings and thanks for the tip

  54. Seriously? 50KB+ of modularized-to-hell, slow JavaScript just to change a stylesheet? The “raw” solution, or real solution as I call it, is about 2KB and doesn’t use 20,000 functions and 20,000 objects to grab an element.

  55. HTML
    Permalink to comment#

    None of this works. Waste of time…

  56. Steven
    Permalink to comment#

    Thanks, this is very very helpful. Is there a way to create the dynamic dropdown using the jquery method if the original menu has some css dropdown such as:

    <ul class="menu">
      <li class="menulist"><a href="/index.php">HOME</a></li>
      <li class="menulist"><a href="page1.php">RUNNING</a></li>
      <li class="menulist"><a href="page2.php">TRIATHLON</a></li>
      <ul class="menu">
      <li class="menulist"><a href="/about-us.php">ABOUT US</a>
      <li class="menulist"><a href="/page3.php">F.A.Q</a>
      </li>
      <li class="menulist"><a href="/page4.php">LINKS</a>
      <li class="menulist"><a href="page5.php">FRAMING</a></ul>
      </li>
    </ul>
    

    as you can see there is a second < ul > in the menu.

  57. Usman Ahmed
    Permalink to comment#

    Oh great! I was thinking that I might need too much scripting for that. But this is not the case. thanks for great tutorial. Now my website is pretty much compatible with mobile devices.

  58. jason
    Permalink to comment#

    what an awesome article. super easy fix for making a great fluid layout. thanks bro!

  59. Alfred
    Permalink to comment#

    WOW thanks alot

  60. Manikandan

    This was really great learning. A difference between max-width and max-device width. This is the trick here everyone should learn.

  61. sergio zambrano

    My main concern is: Will the different linked stylesheets be loaded EVEN if they are out of range for the current device?

    In otherwords, are the linked stylesheets “selected” or “loaded” by device width?

    I’d like them not to be even loaded at all if the current device is outside the specified limits, or if the device or your html have the landscape option disabled (I don’t konw how it’s called when you rotate the device).

  62. Ivan Lollar
    Permalink to comment#

    I tried to write this out and when i tested it nothing happened. I used both the jquery and css media method (together and separately). My main goal is for mainly browser window resizes.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".