Lukas Z's Blog

Use Media Queries in Your CSS Now

So far CSS3 has given web developers some great new features. One of the newest W3C standards are Media Queries. And they should be used right now.

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:

<link rel="stylesheet" type="text/css" href="/stylesheet.css" media="print">

or

<?xml-stylesheet media="print" rel="stylesheet" href="stylesheet.css" ?>

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:

#somediv {
  width: 900px;
  font-size: 16px;
}

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:

#somediv {
  width: 900px;
  font-size: 16px;
}

@media screen and (max-device-width: 800px) { // or something like this
  #somediv {
    width: 90%;
    font-size: 13px;
  }
}

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.

Media Features

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.)
  • device-aspect-ratio
  • 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.

Read more

For more information do visit the official W3C recommendation page for media queries.

P.S.: You can follow me on Twitter.

Comments

Webmentions