The idea is that you can specify style rules in your stylesheets that only apply to devices with certain characteristics. Thus, for example, you can make the same HTML-element render one way in the desktop browser, and another way on the smartphone.
This is fantastic. Some time ago the webserver would parse the HTTP-request to figure out what device the request comes from and serve a different stylesheet. Now we can let the user’s browser worry about that.
How it works
There’s several ways to define device-specific CSS:
- In the link (or ?xml-stylesheet)-element, by adding a media-attribute to the tag.
- In the @import-statement, by attaching a media type.
- As a selector in the CSS-file.
The first two look like this:
And they instruct the browser to use a certain stylesheet under certain conditions. But let’s focus on the third way.
Basically, you just wrap certain elements in @media selectors. For example, let’s say you have a rule like this in your stylesheet:
This would probably look crappy on a handheld, because it would require horizontal scrolling. But now you can simply add another rule that makes the div render differently on a device with a smaller screen. So for example we now have this:
Voilà, this will render a div with 90% parent div-width (let’s say screen width) on an iPhone, but exactly 900px on a desktop. Fantastic. And you can use these queries to change your whole layout, too. Just access this blog with a handheld, and you will see a different layout, without the sidebar etc. Or just make the browser window smaller. You should see the layout change at some point.
I’ve been writing HTML since the 90s, but lately it’s really getting good. Media Queries are definitely one of the reasons.
There’s more than just “max-device-with”. The list includes:
- color (interesting when considering that your page might be displayed on something like a Kindle.)
- orientation (landscape or portrait)
..and so forth. Check out this list. Scroll a little bit up on this page to see a list of media types.
For more information do visit the official W3C recommendation page for media queries.
P.S.: You can follow me on Twitter.