Quick Tip: A Crash-Course in CSS Media Queries
videos

Quick Tip: A Crash-Course in CSS Media Queries

Tutorial Details
  • Topic: CSS Media Queries
  • Difficulty: Easy
  • Estimated Completion Time: 4.5 Minute Screencast
This entry is part 5 of 16 in the CSS3 Mastery Session
« PreviousNext »

In the past, in order to create layouts based upon the width of the user’s browser, we had to use JavaScript — perhaps combined with a server-side language. Fortunately, the process is now becoming far simpler, thanks to CSS media queries.



Method 1: Within your Stylesheet

@media screen and (min-width : 1200px) {
  /* let's do somethin' */
}

Method 2: Import from within your Stylesheet

@import url( small.css ) screen and ( min-width: 1200px );

Note that you can also add addition rules, by applying a comma — much like you would when using multiple selectors.


Method 3: Link to a Stylesheet

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

Method 4: Targeting the iPhone

<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="mobile.css" />

An interesting note, after a bit of research around the web, is that, despite the fact that iPhone 4 sports a resolution of 640×960, it still we pick up mobile.css, referenced in the code above. How strange? If you have more information on this, please leave a comment for the rest of us!


Browsers that Support CSS Media Queries

  • Firefox 3.5+
  • Opera 9.5+
  • Safari 3+
  • Chrome
  • Internet Explorer 9+

Please note that Internet Explorer 8 and below do not support CSS media queries. In those cases, you should use a JavaScript fallback.

Add Comment

Discussion 42 Comments

  1. Eduardo Barros says:

    “Thanks you left the code in the post, I would hate to go throughout 4 minutes of boring just to get the code.”
    Joking, great video, thanks!

  2. It does seem odd that the “max-device-width: 480px” still works for the iPhone 4, when the resolution is higher. I think it has something to do with what they’re calling the “pixel ratio”. The pixel ratio for the iPhone 3G and below is 1, but the pixel ratio for iPhone 4 is 2. So the device width is 480px, but the amount of pixels is 960.

    If you want to target the iPhone 4 through media queries (for high res images or something?), you can use this:

  3. Anderson Juhasc says:

    Parabéns novamente Jeffrey, gosto muito de seus posts.
    Quando eu chegar nos USA quero conhece-lo pessoal mente e
    poder trocar conhecimento, abraço. lang=pt-BR

  4. Jeroen says:

    Nice explaining, and definately worthy to be a quicktip for those who don’t already use this.

    Good work, once again!

  5. Andy King says:

    Thank you, Scriptin, for the link to js for older browsers.

  6. GRolf says:

    I always wonder why one would double the work to a) create those media-queries and b) create a javascript fallback, if solution b) is also supported in the newer browsers. Just go for javascript.

    • Chris says:

      To provide a js-less solution for those that support it in case something does not have javascript on?
      A default stylesheet that works for IE is also a super feasible option, and doesn’t require any js.

      It’s all about progressive enhancement.

  7. Brad says:

    I had absolutely no idea you could do that. Absolutely excellent quick Tip Jeffrey

  8. andrei says:

    Thank you, great cast as always

  9. It Village says:

    thanks to nettuts. which always inspires me.

  10. Thim says:

    Thanks for sharing Jeffrey ! This looks just great :)

  11. w1sh says:

    Cool stuff. Never even heard about these.

  12. Alistair says:

    Whilst it’s great these new techniques are being pointed out. It seems very counter productive to promote using jQuery and media queries. The overhead might be negligible but why increase the bloat. Why not tackle it with jQuery once and be done with it.

    • Jeffrey Way says:

      For a couple reasons:

      1) To know how to do it! This will be standard after one more browser generation.

      2) In the browsers that support media queries, the changing layout won’t be dependent upon JS being enabled.

      3) It helps push the web forward. :)

      • Alistair says:

        This is why I said great you point these things out. Nettuts and other Authors will always have a purpose.

        With that said, anybody keeping up to date will be aware of these techniques from r & d throughout their career.

        Browser support is great, but until it IS the standard i’d rather hit it once with JS and come back another time another day to hit with only CSS.

        I agree, it’s catch 22 sometime the big vendors hold us back and short of a community revolution these things never get implemented. So when you say push, I guess you mean community forcing big vendors to listen up.

    • Mike Hopley says:

      I think it depends on your priorities. You have several options:

      1) Use a javascript-only method. Benefit: reaches the widest audience. Drawbacks: layout depends on JS, mixing presentation with behaviour; initial page rendering may be slower (waiting for the JS, especially if you used a library), with possible disorienting “flash” when the resolution-specific styles kick in.

      2) Use @media with a JS fallback. Benefits: reaches the widest audience; modern browsers don’t receive unnecessary JS. Drawbacks: complicates your code, violating DRY principle; now you have two implementations to test and maintain, rather than one.

      3) Use @media with no fallback (just a fixed-width site). Benefit: progressively enhanced display for modern browsers. Drawback: older browsers don’t get resolution-optimised layouts.

      4) Don’t use either of them. Benefit: only one layout to design, maintain, and test. Drawback: layout is not optimised for different resolutions.

      Personally, I would stick to either (3) or (4). I’m leaning towards (3).

      • Alistair says:

        Whilst it’s small in concept, work requirements are normally quite specific.

        Support of CURRENT (sorry for shouting, italics would be nice) web browsers, support for mobile browsers or a specific fix for legacy.

        Using @media right now is counter productive but when we are 2 versions ahead with full support in all browsers that’s the time to use it imo. Ofcourse the demographic have to use those browsers also.

        None the less, great tutorial and good convo.

  13. cahva says:

    Nice tip Jeff. Whats the thing with you and changing text-editor every 2-3 weeks ;-) Speaking of editors I TRIED to learn Vi/Vim but got frustrated after couple of days.. My memory is so bad that I forget different keycombinations so easily.. I know its powerfull after you get the hang of it, but I’ll stick to nano for quick edits from shell and use other more “mouse oriented” editors otherwise :)

    • Jeffrey Way says:

      @Cahva –

      It’s just a quirk of mine. :)

      Vim is definitely a huge challenge. It continues to frustrate me; but I’m certain that, after a month, the commands will be second nature. :)

  14. 9swords says:

    This is such a useful quick tip, great for problem solving. Good to know that IE9 will support media queries. Many thanks to you Jeffrey.

  15. always cool quick tips :D nice tut, thanks

  16. It’s interesting, altrough I believe the javascript method would be more simple and portable.
    Thanks for the tip!

  17. You should really mention that “Method 1: Within your Stylesheet” is the only method you should EVER use. Why? It’s the only method that doesn’t result in additional HTTP requests, which as you know come with a performance penalty.

  18. devlim says:

    anyone know how to use comma to add additional rules like what jeff say?
    i test and not sure how to do it, i only manage to test out with add “and” instead of “comman” like this

    @media screen and (min-width:900px) and (max-width:999px)

  19. david says:

    hi i need some help please

    i have setup a media querie

    @media screen and (min-width : 1024px) {
    .wrapouter{BACKGROUND: url(../images/contentbox-shadow.png) repeat-y; margin: 0px auto; WIDTH: 1050px}
    }

    which works great

    i have been trying for days to get an overwride for it useing jscript

    i am trying to say if brouser res is >1024

    use

    .wrapouter{BACKGROUND: url(../images/contentbox-shadow.png) repeat-y; margin: 0px auto; WIDTH: 1050px}

    else

    .wrapouter{}

    any help on this matter would be great i just cant get it work with java

  20. Gary says:

    Hmm…nice…I must try this. Thanks.

  21. Karl Munford says:

    Can someone give the ‘easy’ JS method for targeting IE8 and below as mentioned in the tutorial?
    Please leave out nothing and ‘assume’ nothing as I am not familiar with JS. CSS CSS3 reasonable but not really with JS. :)

  22. Frank says:

    Great Work. We will try it. Thanks a lot.

  23. Great crash course. Did you figure out how to make queries to load high res images for iPhone 4?

  24. Jennifer says:

    Thanks for laying it out so well. Quick, demonstrative – nice work! Just what I was looking for.

  25. sawebdesigns says:

    Thanks just what i needed right now

  26. Emily says:

    <3 your cast. Thanks for the info!!

  27. Joe says:

    Thanks for the nice tip on the media queries and a good place to start to use it to support iphone and ipad compatibility of my website.

  28. saurabh says:

    great thanks for helping me

  29. JL says:

    I deal with this all the time for mobile sites.For future reference, here are some device sizes

    * Apple iPhone/iTouch :: 320 x 480
    * Nexus ICS :: 360 x 598 (720 x 1280 screen)
    * Samsung Galaxy S Phone (smaller) :: 480 x 800
    * Samsung Galaxy S Sprint 4g (larger) :: 480 x 800
    * Samsung 4Glte :: 480 x 800
    * Motorola Droid RAZR :: 540 x 960 (?)
    * Nook Color :: 600 x 1024
    * Samsung Galaxy Tab 6 inch :: 600 x 1024
    * Amazon Kindle Fire :: 600 x 1024
    * Apple iPad :: 768 x 1024
    * Samsung Galaxy Tablet :: 800 x 1280

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.