Building Mobile Interfaces with Media Queries

10 Building Mobile Interfaces with Media Queries

We’ve been able to define media-specific style sheets for quite a while, but we’ve been limited to the type of output, as you saw in Making

Links Printable with :after and content , on page 83 , when we defined our print style sheet. CSS3’s media queries 6 let us change the presentation of a page based on the screen size our visitors use. Web developers have done screen size detection for years using JavaScript to obtain information about the user’s screen size. But we can start to do that with style sheets alone. We can use media queries to determine the following:

• Resolution • Orientation (portrait or landscape mode) • Device width and height • Width and height of the browser window

Because of this, media queries make it very easy for us to create alter- native style sheets for mobile users.

It turns out that the AwesomeCo executive staff have all just dumped their BlackBerry devices for shiny new iPhones. The marketing director would love to see an iPhone-ready version of the blog template we built

in Redefining a Blog Using Semantic Markup, on page 27 . We can do that very quickly.

Our current blog is a two-column layout, with a main content region and a sidebar. The easiest way to make this more readable on the iPhone is to remove the floating elements so that the sidebar falls be- neath the main content. That way, the reader won’t have to scroll side- ways on the device.

6. http://www.w3.org/TR/css3-mediaqueries/

B UILDING M OBILE I NTERFACES WITH M EDIA Q UERIES 95

Joe Asks. . .

What About the Handheld Media Type? The Handheld media type was designed to let us target mobile

devices like we target printers, but most mobile devices want to show you the “real Internet” and so they ignore that media type, serving the style sheet associated with the screen media type instead.

To make this work, we’ll add this code to the bottom of the blog’s style sheet:

Download css3mediaquery/style.css

@media only screen and (max-device-width: 480px) { body{ width:460px; }

section#sidebar, section#posts{ float: none; width: 100%;

You can think of the code we put within the media query braces as its own style sheet, invoked when the conditions of the query are met. In this case, we resize the body of the page and turn our two-column layout into a single-column layout.

We could also use media queries when we link the style sheet, so we can keep our mobile style sheet in a separate file, like this:

<link rel= "stylesheet" type= "text/css" href= "CSS/mobile.css" media= "only screen and (max-device-width: 480px)" >

With that, our blog immediately becomes more readable on the iPhone. You can use this approach to build style sheets for other displays as well, such as kiosks, tablets, and displays of various sizes so that your content is readable in more places.

B UILDING M OBILE I NTERFACES WITH M EDIA Q UERIES 96