Try Tuts+ Premium, Get Cash Back!
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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Eduardo Barros

    “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!

  • http://www.russelluresti.com RussellUresti

    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:

    • http://www.russelluresti.com RussellUresti

      Let’s try that code block again, shall we?

      • http://www.russelluresti.com RussellUresti

        … I hate you, comment system. I really, really do.

        <link rel=”stylesheet” media=”screen and (-webkit-min-device-pixel-ratio:2)” href=”iphone4.css” />

      • http://taylorhutchison.com Taylor Hutchison

        Great quick tip!

        and thanks Russell for finding that webkit specific setting.

      • http://twitter.com/irengba irengba

        wow.. thanks for the tip.

  • Anderson Juhasc

    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

  • Jeroen

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

    Good work, once again!

  • http://dmitry-scriptin.blogspot.com/ Scriptin

    For IE6-8 use css3-mediaqueries-js

  • Andy King

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

  • GRolf

    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.

    • http://www.material-designer.com Chris

      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.

  • Brad

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

  • http://linknomer.com andrei

    Thank you, great cast as always

  • http://itvillage.site11.com It Village

    thanks to nettuts. which always inspires me.

  • http://twitter.com/thimmpa Thim

    Thanks for sharing Jeffrey ! This looks just great :)

  • w1sh

    Cool stuff. Never even heard about these.

  • http://pixelcoder.co.uk Alistair

    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.

    • http://net.tutsplus.com Jeffrey Way

      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. :)

      • http://pixelcoder.co.uk Alistair

        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

      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).

      • http://pixelcoder.co.uk Alistair

        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.

  • cahva

    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

      @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. :)

  • http://zubeta.com/beta/ 9swords

    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.

  • http://www.eclipsedesign.eu Kartlos Tchavelachvili

    always cool quick tips :D nice tut, thanks

  • http://thedevelopertuts.com Bratu Sebastian

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

  • http://mathiasbynens.be/ Mathias Bynens

    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.

  • http://www.code.my devlim

    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)

  • david

    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

  • http://www.webdesigncrap.info Gary

    Hmm…nice…I must try this. Thanks.

  • http://www.esculent.co.uk Karl Munford

    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. :)

    • http://www.jeffrey-way.com Jeffrey Way
    • Jerodq

      I will second Karl’s question. I have found about a dozen different articles telling people to use “css3-mediaqueries.js” to support IE, but nobody has explain how to do that to those of us that are familiar with html and css, but new to the javascript world.

      If anybody out here can explain how, that would be extremely helpful. Thank you.

  • http://radio-pr.com/ Frank

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

  • http://www.digitalfrontend.com Eduardo Martinez

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

  • http://busybeeonabudget.com Jennifer

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

  • http://www.sonnydesign.com sawebdesigns

    Thanks just what i needed right now

  • Emily

    <3 your cast. Thanks for the info!!

  • http://www.codelabgh.com Joe

    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.

  • saurabh

    great thanks for helping me

  • JL

    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

    • Jey

      what is about IPhone5?

    • Jey

      What about IPhone5 device size?