Working with media queries

The use of media queries simply allows us to apply different CSS styles based on resolution and/or device orientation. It uses the same old media declaration that we’ve used for serving up print stylesheets but now it just has a few more features under its belt.
Everyone’s doing it… ok, so maybe not everyone but it’s definitely starting to gain some traction amongst the designers who are prepared to push the boundaries – or at the very least experiment with them from time to time.
Hicks Design

How do we use them?

First we need to set the viewport to device-width
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Then we can either link to external stylesheets
  1. <!--[if !IE]>-->
  2. <link type="text/css" rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" />
  3. <link type="text/css" rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px)" href="ipad.css" />
  4. <!--<![endif]-->
Or we can add them to an existing stylesheet
  1. /* target the minimum width of the browser window */
  2. @media screen and (min-width: 900px) {
  3. .class {
  4. background: #FFE11A;
  5. }
  6. }
  7.  
  8. /* target the maximum width of the browser window */
  9. @media screen and (max-width: 600px) { }
  10.  
  11. /* target both the minimum and maximum width of the browser window */
  12. @media screen and (min-width: 600px) and (max-width: 900px) { }
  13.  
  14. /* target the maximum width of the device */
  15. @media only screen and (max-device-width: 480px) { }
  16.  
  17. /* target the maximum width of the device and it's orientation */
  18. @media only screen and (max-device-width: 480px) and (orientation:portrait) { }
  19. @media only screen and (max-device-width: 480px) and (orientation:landscape) { }
  20.  
  21. /* target the iPhone4 retina display */
  22. @media only screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) { }

Is it supported?

The browser support for media queries is actually pretty good. The latest versions of Firefox, Safari, Chrome, and Opera are all using it. Internet Explorer 9 will be, but IE8 and below do not :( however there is a jQuery media queries plugin – for those not-so-capable browsers.

Final thoughts

One thing to keep in mind – Although we can now tailor our designs to suit different devices we’ll still be dealing with the exact same content. (CSS3 flexbox can help rearrange some content if necessary) So even if we decide to use CSS to hide images on the iPhone, they’ll still be downloaded by the user.

Notable Mentions

  • Mediaqueri.es – A collection of responsive web designs.
  • Less Framework – A CSS grid system for designing adaptive web­sites.
  • CSSgrid – A 1140px wide, 12 column grid. Fluid all the way down to a mobile version.
  • A Jason Grigsby article – On media queries for mobile being fools gold.
Ed Merritt
Simon Collison