Grow your CSS skills. Land your dream job.

CSS Media Queries & Using Available Space

Published by Chris Coyier

We've covered using CSS media queries to assign different stylesheets depending on browser window size. In that example, we changed the layout of the entire page based on the space available. It isn't required that we make such drastic changes with this technique though, so in this tutorial we'll go over a design tweak with a smaller scope. We'll also cover the syntax for using media queries within a single stylesheet and more examples of that.

The CSS media query syntax for calling an external stylesheet is like this:

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

You may be familiar with the media attribute, normally being "screen" or "print" or even a comma separated list, like "screen, projection". The media attribute can be brought directly inside a CSS file, like this:

@media screen {
  body {
    width: 75%;
  }
}

@media print {
  body {
    width: 100%;
  }
}

Likewise, you can use more advanced CSS media queries like:

@media all and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
  body {
    background: #ccc;
  }
}

You may use as many media queries as you would like in a CSS file. Note that you may use the and operator to require multiple queries to be true, but you have to use the comma (,) as the or operator to separate groups of multiple queries. The not keyword can be used to alter the logic as well.

Example

Let's say we have a fluid width design where the sidebar is 35% of the width of the page. That means depending on the width of the browser window, that sidebar could be quite narrow or quite wide, that's just the nature of fluid width designs. With CSS media queries, we can say "if the browser is really narrow, do this, if it's wider, do this, if it's really wide, do this." Note that measuring width isn't the only thing media queries can do, it's just a particularly practical example.

In our example sidebar, we are going have a list of names of the Super Team which function as email links. The HTML is fairly simple:

<ul id="nav">
   <li><a data-email="chriscoyier@gmail.com" href="mailto:chriscoyier@gmail.com">Chris Coyier</a></li>
   <li><a data-email="elisabeth@moss.com" href="mailto:elisabeth@moss.com">Elisabeth Moss</a></li>
   <li><a data-email="amanda@righetti.com" href="mailto:amanda@righetti.com">Amanda Righetti</a></li>
</ul>

It's just a list of links. The href attribute is a mailto:</ttcode link. The only thing you might find unusual is the <code>data-email attribute. In HTML5, you can use attributes prefixed with data- to store information, and it's perfectly valid. We are going to want to use that data later, but the href value isn't quite what we need having that mailto: link, hence the data attribute.

The default styling for the list will be this:

#sidebar ul li a {
  color: #900;
  text-decoration: none;
  padding: 3px 0; 
  display: block;
}
At narrow browser window widths, the default styling applies. Just a list of links.

When the browser gets a bit wider, in our example between 520 and 699px, we're going to use that extra space that opens up in the sidebar to apply an email icon to each list item.

@media all and (max-width: 699px) and (min-width: 520px) {
  #sidebar ul li a {
    padding-left: 21px;
    background: url(../images/email.png) left center no-repeat;
  }
}
Icons are applied to the list items as we know that we have room for them now.

As we get wider, from 700 to 1000px, we'll use the extra space again to preface the links with the text "Email: " (using CSS Content) instead of just the icon.

@media all and (max-width: 1000px) and (min-width: 700px) {
  #sidebar ul li a:before {
    content: "Email: ";
    font-style: italic;
    color: #666;
  }
}
Using CSS content / psuedo element, we can preface the link with descriptive text without altering the content in the HTML

Wider still, at browser window widths above 1001px, we'll literally append the email address to the links. This is where that HTML5 data attribute comes in.

@media all and (min-width: 1001px) {
  #sidebar ul li a:after {
    content: " (" attr(data-email) ")";
    font-size: 11px;
    font-style: italic;
    color: #666;
  }
}
Again the content is adjusted, the email is added as a pseduo element purely with CSS.

At really wide widths, above 1151px, we will again add the icon as we used before. The cool part here is that we don't have to write an additional media query segment, we can just append an additional media query to our already existing one using a comma (behaves like OR operator) on the medium-width one we already wrote.

@media all and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
  #sidebar ul li a {
    padding-left: 21px;
    background: url(../images/email.png) left center no-repeat;
  }
}
At the widest, we can use all the flair we have available.

All together now

#sidebar ul li a {
  color: #900;
  text-decoration: none;
  padding: 3px 0; 
  display: block;
}

@media all and (min-width: 1001px) {
  #sidebar ul li a:after {
    content: " (" attr(data-email) ")";
    font-size: 11px;
    font-style: italic;
    color: #666;
  }
}

@media all and (max-width: 1000px) and (min-width: 700px) {
  #sidebar ul li a:before {
    content: "Email: ";
    font-style: italic;
    color: #666;
  }
}

@media all and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
  #sidebar ul li a {
    padding-left: 21px;
    background: url(../images/email.png) left center no-repeat;
  }
}

Video demo

Live demo / download

View Demo   Download Files

Browser support

The browser support for media queries is surprisingly decent. For the queries in this particular demo (utilizing min and max widths), current version of Firefox, Safari (including Mobile), Chrome, and Opera are all supporting it. Internet Explorer 9 will be supporting it, but 8 and below do not. If I wanted to deliver the best possible experience in IE 8 and below, I'd either fake it with JavaScript like I did in this article, or use an IE specific stylesheet and style it in the same style as the most common browser width according to analytics.

Note that milage may vary on individual types of queries. For example, the iPhone supports the width queries but does not support the orientation queries. The iPad supports both.

More on media queries

Measuring width is a nice practical example of media queries, but it isn't the only thing available. Below are some more of them (not a comprehensive list). The spec lists lots more.

Types

HTML4 had these media types, which are all still valid: aural, braille, handheld, print, projection, screen, tty, and tv. HTML5 may include more as it needs them. The spec includes ‘3d-glasses’, which is awesome. The all keyword will target all types.

@media screen, projection { ... }

Dimensions

You get height and width, which query against the current browser window height and width. You could use them as-is, but that would probably be rare. Both of them accept min/max prefixes, so more commonly you'd used them as min-width, max-width, min-height, max-height.

There is also device-width and device-height, which also provide min-device-width, max-device-width, min-device-height, and max-device-height.

@media (min-device-width: 640px) { ... }

Orientation / Aspect Ratio

You can query against the aspect ratio of the screen as well with device-aspect-ratio.

@media screen and (device-aspect-ratio: 16/9) { ... }

Or if the screen is in portrait (height larger than width) or landscape (width larger than height) mode.

@media (orientation:portrait) { ... }

Color

You can query on if the screen is in color or not and details about that.

@media (color) { /* Screen is in color */ }

@media (min-color-index: 256) { /* Screen has at least 256 colors */ }

@media (monochrome) { /* Screen is monochrome */ }

Elsewhere

This has been a hot topic lately. You can hear some smart people talk about it on The Big Web Show. Here are some other cool uses of it going around recently:

  • Andy Clarke shows how the the longer the line length the more readable text can be with taller line height.
  • Jon Hick's site rearranges itself to have double sidebars, single sidebar, or no sidebar according to available space. It even scales down to mobile sizes nicely.
  • Ethan Marcotte's demo for A List Apart doesn't use media queries, but shows other ways a design can be effectively flexible.
  • Simon Collison's site rearranges it's grid to fit different browser sizes.
  • Panic uses @media in their HTML emails to make them look awesome in desktop or mobile email clients.

Comments

  1. Excellent implementation, I’ll be sure to note this for future development.

  2. Thats a very cool technique. I have to hand it to you Chris the quality of your articles has really went up lately. Keep up the good work!

  3. Dig the new “Video Demo” (not sure if that’s new or not but I just noticed it).

    Thanks for the awesome tip!

  4. bill

    You may want to point out that CSS media queries don’t work in IE8 and below and are part of the W3C’s current CSS3 recommendation (http://www.w3.org/TR/css3-mediaqueries/).

  5. Ant

    This jq plugin may be used for IE:

    http://protofunc.com/scripts/jquery/mediaqueries/

  6. Very cool technique, thank you for putting this together.

  7. Toni Kukurin

    Although I did know about this nifty trick for quite a while now, I must admit it never really occurred to me I could (should) use it.

    It’d probably be interesting to see grid layouts (Blueprint, for instance) using this technique. Imagine; 950px and above get the whole thing, everything below gets a smaller version.

    I’m absolutely putting it on my to-try list!

  8. I like using icons; they say a lot in so little space.

    great write up. there are things i have not considered until now.

  9. Great technique. Thanks Chris !

  10. Nice technique, but what about usage in the real world project, where only very few visitors can have a benefit of it? Maybe in 4-5 years?

    • Ant

      http://cg.tutsplus.com/ is the only site I’ve seen using that (with scripts though).

      I’d say it’s better than fluid layout, because more control of placing and resizing elements.

  11. Great Article! Thanks Chris:)

  12. Ewald

    Great Article! I love it, Chris!

  13. Miles

    @ the panic example

    I haven’t followed Mozilla’s work all that closely and I don’t really know that much about the rendering engines in most email clients:

    I know that Thunderbird uses Gecko, but I don’t know what version or does anyone have any analytics on what versions are in the wild? Does Apple Mail use webkit?

    This would be very useful, but is there any resource on the web that talks about what email clients are capable of approaching the level of detail that we have for the major browser vendors?

    • Toni Kukurin

      Basically, they use the same browsing engine their counterparts (ehm… Web browsers) use.

      IE and Outlook = Trident,
      Apple Mail = Webkit,
      Thunderbird = Gecko.

      More info on The Dot Product. ;)

    • I hate to be a nag, but Outlook most certainly does NOT use IE/Trident for HTML rendering. Outlook uses (wait for it…) Microsoft Word to render HTML in emails, which is the EXACT reason it renders HTML like it’s still 1996 or something!

      Cheers!

    • Toni Kukurin

      Yes, I forgot to include that it USED to have that engine.

      If you look at the site I’ve included (The Dot Product), even there it says they’re now using Word’s rendering engine. ;)

  14. Alexander

    There is a jQuery Plugin wich enables basic media queries support in IE/old browsers:

    http://protofunc.com/scripts/jquery/mediaqueries/

    You don’t need to write one extra line of JavaScript-Code or add some strange markup for this. The plugin simply parses the media attribute of your linked stylesheets and attaches the right styles sheets, dynamically.

  15. Those are some really neat tricks, that opens up quite a few possibilities for fluid designs.
    I salute you!

  16. wonderful tut!!! very good work!!

  17. bewa

    id like amanda to marry me too :D

    nice tut! keep up the good work!!

  18. maria

    !amazing post!

  19. thanks for sharing!!!

  20. Chris,

    Great article! I’ve been thinking a lot about media queries lately, so it’s cool to see it all laid out here, clear and concise. I’m also glad you mentioned the “CSS Content” ideas too. Regarding the “CSS Content” feature, I think another cool (possibly more useful) idea would be to change the email icon to text if images are turned off. Just my two cents.

  21. Marcus Tucker
    Permalink to comment#

    Nice article, my only criticism is that it doesn’t mention that media queries are new to CSS3 and are therefore only correctly interpreted by browsers which support CSS3, unless you use the JS shim others have already mentioned to expand support to older browsers.

  22. jean marc
    Permalink to comment#

    Thx, gonna try an Iphone /Ipad web view…

  23. As per normal, tutorial is right on cue with where I am on my current project! Nice timing!

  24. very cool indeed and thank you for sharing for how much work did you spend in it? and for a single element!

    if you use this technique in a project that is more than a single page you most likely will have to do the same for many elements.

    it is really worth??

    the answer is, of course: Depends

    if this will spare you the work to create a completely different version of your website for let’s say mobile devices, then definitively YES, if not, who cares?

  25. asccigcc
    Permalink to comment#

    Man, this is awesome, i will try this, thnx.

  26. Permalink to comment#

    This is awsome stuff. really it is. I’ve played with overlow properties to acheive similar results i interfaces…
    …but to say this is well suported when no current IE supports this is um…well it’s maybe right if your site is for designers only.

    IE sadly having huge market share and looking like it will only slip gradually http://netmarketshare.com/browser-market-share.aspx?qprid=2

  27. Great post, thanks,very useful really.Thanks again.

  28. Just a note about the last part of the article “Elsewhere”:
    Ethan Marcotte’s demo does use media-queries: in the final version of the layout:
    http://www.alistapart.com/d/responsive-web-design/ex/ex-site-FINAL.html

  29. Permalink to comment#

    Thanks Chris for great post! When I read your posts, I feel I need carry on practice. =) I wish you all the best!

  30. nish
    Permalink to comment#

    hello thanks for the post its really helpful! but is http://www.opera.com using the same concept?or using grids?

  31. Is there a reason why you are using @media all and (max-width:...) when all is already implied?

    I noticed a few days ago that I have been using all in every @media rule and can’t figure out why I did that. It seems to be common practice for everyone, maybe someone know why?

  32. BRIAN
    Permalink to comment#

    You just saved my life. You’re my hero man. GREAT ARTICLE!!!!

  33. Kursus
    Permalink to comment#

    Hi, I wanna ask about css media print, what for?

  34. Shahbaz Ahmed Bhatti
    Permalink to comment#

    He CSS-Tric i very like Chris, Chris is the Hero of CSS. Keep it up Thank u Sir

  35. Permalink to comment#

    Hey Chris,

    I know this is a very old post, but i have to ask. You have mentioned we can target device-height also. So i can design according to the height of the device? Has it got any flaws ?. Ive used device-width to good effect, however i would like to know whether device-heigth is a good choice. I want to target the phones with small size espcially length-wise. Over my part of the world, such devices are common and im forced to vary my layout according to the height also. Looking forward to hearing back from you.

    Thanks
    Roy M J

  36. Ian
    Permalink to comment#

    I am so glad I found this post. This has totally revolutionized my knowledge base. You rock.

  37. Hello there! I simply wish to offer you a big thumbs up for the
    excellent information you have got here on this post.

    I’ll be returning to your website for more soon.

  38. Hey Chris,
    I’ve used CSS-Tricks an unknown amount of times, and I recently watched the awesomely motivational talk you gave (the rolling rock infused writers block, work smart, sass, etc). I’ve been aware of responsive design, but I usually used a max-width property (I know I know). You explain media queries like a boss in this article, if you ever find yourself in the panhandle of West Virginia I believe I owe you several cases of rolling rock!

  39. Maggie

    Great post! Kinda creepy sample email addresses.

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