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="[email protected]" href="mailto:[email protected]">Chris Coyier</a></li>
<li><a data-email="[email protected]" href="mailto:[email protected]">Elisabeth Moss</a></li>
<li><a data-email="[email protected]" href="mailto:[email protected]">Amanda Righetti</a></li>
</ul>
It’s just a list of links. The href
attribute is a mailto:
link. The only thing you might find unusual is the 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;
}

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;
}
}

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;
}
}

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;
}
}

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;
}
}

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
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.
Excellent implementation, I’ll be sure to note this for future development.
I literally relaunched my site today using @media queries. Feel free to check it out. All the CSS is in the page as it’s a tumblr theme.
http://stream.andycroll.com
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!
Dig the new “Video Demo” (not sure if that’s new or not but I just noticed it).
Thanks for the awesome tip!
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/).
I did, in the section “Browser Support”
…along with other browser support information. =)
You may want to read the entire article before commenting. ;)
Tony, you may want to not come off like a tool. Whoops, too late!
Haha gold!
This jq plugin may be used for IE:
http://protofunc.com/scripts/jquery/mediaqueries/
Very cool technique, thank you for putting this together.
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!
I like using icons; they say a lot in so little space.
great write up. there are things i have not considered until now.
Great technique. Thanks Chris !
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?
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.
Great Article! Thanks Chris:)
Great Article! I love it, Chris!
@ 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?
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!
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. ;)
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.
Those are some really neat tricks, that opens up quite a few possibilities for fluid designs.
I salute you!
wonderful tut!!! very good work!!
id like amanda to marry me too :D
nice tut! keep up the good work!!
!amazing post!
thanks for sharing!!!
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.
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.
Thx, gonna try an Iphone /Ipad web view…
As per normal, tutorial is right on cue with where I am on my current project! Nice timing!
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?
Man, this is awesome, i will try this, thnx.
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
Great post, thanks,very useful really.Thanks again.
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
Thanks Chris for great post! When I read your posts, I feel I need carry on practice. =) I wish you all the best!
hello thanks for the post its really helpful! but is http://www.opera.com using the same concept?or using grids?
Is there a reason why you are using
@media all and (max-width:...)
whenall
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?You just saved my life. You’re my hero man. GREAT ARTICLE!!!!
Hi, I wanna ask about css media print, what for?
He CSS-Tric i very like Chris, Chris is the Hero of CSS. Keep it up Thank u Sir
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
I am so glad I found this post. This has totally revolutionized my knowledge base. You rock.
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.
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!
Great post! Kinda creepy sample email addresses.