Chapter Fourteen: Targeting Media with CSS

For many years, developers could safely assume that the platforms their readers were using would be similar to one another: they would have a certain screen size (640px × 480px, 800px × 600px, and so on), screen resolution, color depth, and so on. So developers built sites with a core set of platform characteristics in mind. We assumed everyone had color devices—when was the last time someone used a monochrome device to surf the web... ah yes, the Kindle—rather large minimum screen dimensions (1024px × 768px or higher), a relatively low resolution (72 or 96dpi), and so on. Essentially we assumed users would view our sites using something like a desktop computer or laptop.

But something has happened to the web landscape in the last few years. The diversity of devices that people are using to browse the web has increased significantly, and this is a trend that will only accelerate over time. It’s no longer far-fetched to suggest that PCs and laptops will be the minority of devices used for browsing the web sometime in the next five years. There has been an explosion of first-class web experiences on mobile devices like the iPhone, the Palm Pre, Nokia’s S60 platform, the Nintendo DSi, and other handheld devices; game machines like the Nintendo Wii, which supports a version of Opera optimized for TV use; internet-enabled televisions like the Panasonic Viera, some versions of which also feature an Opera browser; the high-resolution but monochrome Kindle; and many other devices, all of which are bringing the web to users in a much wider range of formats and locations than we’re used to.

The traditional “one size fits all” approach of web development—one that assumes relatively large-screened, low-resolution, full-color devices—will soon make little sense.

Traditionally, we’ve had a number of options for targeting various devices using CSS:

• The delightfully named user-agent sniffing, in which we use JavaScript to detect the version of the browser and serve a style sheet based on this information. User-agent sniffing can also be done on the server.

• Hacks that rely on browser bugs to hide or show a style sheet to a browser (we covered this in some detail in Chapter 7).

• CSS @media rules and links to different style sheets based on media types in HTML 4.01.

Let’s take a closer look at these approaches.

User-Agent Sniffing

User-agent sniffing is something to avoid, for a number of reasons.

• Client-side browser detection relies on JavaScript being enabled, and a surprising percentage of web users (five percent or more, according to www.w3schools.com/browsers/browsers_stats.asp) have JavaScript disabled, particularly in larger organizations and in the financial sector.

• Browsers lie. Because so many developers have used this technique badly in the past, thus effectively excluding or downgrading the experience of users of unsupported browsers (even if their browsers could cope perfectly well with the site), many browsers spoof their identity, typically pretending to be Internet Explorer. As a consequence, determining the actual identity of a browser can be very tricky.

• Browsers improve. Just because a version of a browser did not support a feature, or otherwise failed to display your site well, this does not mean that it always will. Using browser detection means keeping track of an ever more complicated matrix of browsers and versions over time. And that’s without beginning to worry about mobile devices, gaming machines, TVs, eBook readers, web-ready refrigerators, and so on.

Hacks

Using browser hacks might occasionally be worth the effort and risk for very specific situations such as working around a particular browser bug, but for serving different style sheets to different browsers based on their media types, it’s really not a solution.

So, is there a solution? Yes. You guessed it: CSS3 media queries.

Media Queries

As we saw in Chapter 4, HTML has supported the ability to link to different style sheets based on the media type of the display (Screen, Print, Handheld, Projector, TV, and so on) since version 4. It was a good idea in theory, but not widely used in practice, largely because with the exception of the Print media type, the Projection media type in Opera, and a small number of mobile browsers with the Handheld media type, browsers haven’t really supported the technology.

CSS3 introduces a much more sophisticated, flexible mechanism for targeting different media according to such features of a device as its width, height, orientation (portrait or landscape), and resolution. The media query mechanism is based on the same concepts and syntax as HTML 4 media types, and has been cleverly designed so as to be backward compatible with today’s browsers.

It’s important to understand how this differs from browser-focused approaches to compatibility we’ve seen in earlier chapters. With media queries, we don’t target specific browsers. Rather, we tailor visual designs for a given media type, regardless of the browser being used to display the page. With this method, we can take into account small screen sizes in some devices, high-resolution screens in others, low-resolution screens in still others, and so on. We can even design for combinations of these features—for example, we might tailor a style sheet specifically for small, high-resolution, monochrome screens.

Here’s how media queries work: rather than simply specifying a targeted type of media from a limited predefined set (as in HTML 4 and CSS2), CSS3 media queries allow you to specify the characteristics of the device you are targeting. For example, you might want a specific style sheet for devices with a maximum screen width of 800px × 600px, that aren’t handheld devices, or one style sheet for printing to color printers, and another for printing to black-and-white printers.

In addition to the familiar HTML 4 media types, such as Print, Screen, Handheld, and so on, CSS3 media queries introduce a number of media features including:

width: the width of the viewport—the viewport is typically the window, but for some devices, such as the iPhone (which has no windows), it’s the device width

height: the height of the viewport (see above)

device-width: the width of the entire screen—or in the case of print, the page); for devices like the iPhone, this will be the same as the width

device-height: the height of the device or page

resolution: the pixel density of the device—for example, the typical resolution for common operating systems is 72dpi for the Mac OS, 96dpi for Windows, 160dpi for the iPhone, and 163dpi for the iPod touch

color: the number of bits per color component (the value will be 0 for monochrome devices)

monochrome: the number of grayscale bits for the device (the value will be 0 for color devices)

CSS3 media queries also include logical operators like and, not, and or, and the prefixes min- and max-. The media features, along with these operators, let us form expressions that narrow the scope of the HTML 4 media types. An example media query might be:

image

An expression is contained in brackets, and each expression is either true or false. A device with a width of 600px and a height of 900px won’t be targeted by the media query in the example above, because while it matches the first expression, it doesn’t match the second.

Using Media Queries

Like media types in HTML 4 and CSS2, media queries are used with either @media statements, or as the value of a media attribute of a link element in the head of an HTML document. In the media attribute or @media statement, we specify the criteria we want the media to meet in order for the @media statement or linked style sheet to be used.

For example, we might want a style sheet to be served only when a page is to be printed in color. For this example, we’d use a statement like this:

image

The preceding example tells a device to use only the @media statement for printed media, and only for color devices.

Similarly, if we want a linked style sheet to be used only when the window is greater than 800px wide, we can use the following:

image

And if you wanted to use a linked style sheet only when the device window is less than 800px wide, you could use this:

image

Media queries are cleverly designed so that older browsers can still use them to an extent. A browser which only recognizes the older keywords like “print” and “all” will recognize the first word it sees—for example, “screen”—but once it sees a keyword like “and,” it will ignore the rest of the statement. This allows us to use media queries for newer devices that recognize them, and older ones that don’t. Browsers that don’t support CSS3 media queries, but do support older style media statements will see @media print and (color), and treat it like a standard print style sheet.

We can even use media queries to specifically target a device, such as the iPhone, by targeting its particular features. For example, this statement:

image

targets the iPhone in landscape mode—and other devices with a device width of exactly 480px—while this:

image

targets devices with a width of 320px, like the iPhone in portrait mode.

Why the only, you ask? Well, all is the default value for a media type, so if we simply use this statement:

image

then older browsers might use this statement, seeing it as:

image

Similarly, we can hide a style sheet from a device with a maximum device-width of more than 480px (including, of course, the iPhone) using this code:

image

We can also make our media queries even more specific. For example, if we wanted to specify only devices with a device width of exactly 480px in portrait mode, we could use:

image

To bring all these examples together, media queries take the format of a comma-separated list of entries. Entries may be media types (like Print and TV, and so on, specified in CSS2 and HTML 4) or expressions comprising an optional media type (such as screen) plus a logical statement about the features the device must support to use this style sheet or @media rule (such as max-width: 480px). These logical expressions are contained within brackets, as in the preceding example:

image

@media rules are widely supported, and CSS3 media queries are currently supported by Safari 3 and higher (including Mobile Safari in the iPod touch and iPhone), Opera 9.5, and Firefox 3.5 or higher.

Many of these features, like device-width, resolution, or color depth might seem to be fixed for each device, but that’s not necessarily true. Rotate a device like the Palm Pre or iPhone, and it changes page orientation from landscape to portrait—or vice versa—and takes on a new device-width at the same time. Similarly, although it’s more uncommon for users to change the resolution on a device, such as an external monitor, doing so will still change the device-width, even while a page is displaying. Even moving a browser window from one screen to another in a multi-monitor setup will almost certainly change the resolution, and quite possibly other features as well. And, of course, the width of a page can be changed on a desktop browser by resizing the window.

Given this inherent instability in device characteristics, the question arises: if features change while a page is displaying, when will the browser redraw the page using the new value for the media queries? The specification is silent on this issue, so it’s up to the browser implementers to make a decision. Firefox 3.5 and Opera 10 beta generally redraw a page when the window is resized, regardless of which features are associated with a media query. Safari seems to redraw a page after the window is resized only when width is part of the media query—if other features (like resolution or device width) are part of a media query but width is not, Safari only redraws the page on reload. So we can’t rely on the browser to redraw the page based on a media query if features of the device change after the page is loaded. The sole exception seems to be device-width, which prompts Safari, Firefox, and Opera to redraw the page based on the media query when the window is resized.

What Are Media Queries Good For?

CSS3 media queries are intended to let developers tailor the presentation of content to the device presenting that content, rather than serving different content to different devices. Still not convinced of their usefulness? Read on.

Even as monitor (and laptop) screen sizes and resolutions get larger, a new breed of small-screened netbooks has evolved, and mobile devices like smart phones offer yet smaller screens. Optimizing page layout across this broad range of widths is becoming increasingly challenging. Many developers use a JavaScript-based technique Cameron Adams calls “resolution dependent layout” (www.themaninblue.com/writing/perspective/2004/09/21), which involves changing the number of columns in a layout based on the width of a browser window. With media queries, you can achieve this effect without JavaScript.

Here’s how: as the length of a line of text increases, the text eventually becomes harder to read, so we need a way of serving shorter line-lengths for users with big screens, without neglecting users of smaller screens. Using a CSS3 media query with max-width, we can specify, for example, that:

• window widths of more than 1280px will get three columns of text,

• window widths of between 800 and 1280px will get two columns of text, and

• even narrower window sizes will get a single column of text.

This approach will keep the line length from getting too long for readability, and yet ensures lines don’t become too short, which can also reduce readability. To accomplish this, we’ll use two @media statements (or two links to different style sheets): one for widths of at least 1280px, and another for widths of at least 800px. Let’s revisit the multi-column text example from Chapter 13, and force it to adapt to different window widths:

image

We will also have a base rule for the aspects of the layout that we want to serve to all devices:

image

Depending on the user’s window width, they’d see one, two, or three columns, as figures 14.1, 14.2, and 14.3 show.

14.1 Our content will display with three columns at widths greater than or equal to 1280px.

image

14.2 Two columns at widths between 800px and 1280px

image

14.3 And a single column at widths less than 800px

image

As we saw a moment ago, in browsers that support media queries and multi-column text features, the number of columns will change as the width of the window changes.

An even more obvious reason to use media queries is to target mobile devices. This can come in handy not simply for different layouts, but also for developing lighter pages that download faster and use less bandwidth.

As we saw, CSS2 and HTML 4 introduced a number of media types, including Handheld. So, why not simply use that? For a variety of reasons, mobile WebKit-based browsers (which include, of course, Mobile Safari on the iPhone and iPod touch) don’t identify themselves as handheld devices, and so don’t use linked style sheets or @media statements that have a media type of Handheld. Since there’s no specific media type to which all mobile devices definitely belong, how else might we use one or more media features to specify a mobile device?

In this case, we are going to have to make an assumption—for example, that mobile devices will have screens of less than 500px in width. We’ll also want to ensure that older browsers that don’t support media queries won’t use this style sheet. To do that, we’ll use the only keyword as one of the media features, and a max-width of 500px.

image

In fact, this example demonstrates why media types like Mobile aren’t necessarily a sensible way of specifying a style sheet to be used with a given device. That approach is built on the assumption that all devices of a particular type—mobile, projection, print, TV, and so on—will share common characteristics with other devices of the same media type. But of course, devices within a particular media type may vary dramatically in terms of width, resolution, and other features. It’s far better to focus on the particular characteristics of the device, using features that let us tailor a design to the user’s current browsing setup, regardless of the actual device being used.

As the web becomes accessible on an ever-increasing array of devices with different characteristics, media queries can provide a stable, backward- and forward-compatible mechanism for targeting these devices.

Compatibility

CSS3 media queries are widely supported in Safari 3.1 and higher, Opera 9 and higher, and Firefox 3.5 and higher. Not every media feature of CSS3 media queries is supported in each of these browsers.

But Is This Really Any Better Than User-Agent Sniffing?

You may be wondering, Just how are these complicated-looking media queries any better than user-agent sniffing? Happily, the answer is simple. Whereas user-agent sniffing targets specific browsers or browser versions, media queries target specific media and—more importantly—device characteristics, regardless of what browser displays the page. After all, even today, Opera might be running on a laptop, a mobile device, the Wii, or a television. A WebKit-based browser might be running on a mobile device or laptop, as might Internet Explorer and Firefox. All other problems aside, user-agent sniffing just isn’t up to coping with the huge variety of user agents on the web.

Furthermore, whereas user-agent sniffing is often used to work around buggy CSS support in specific browsers, media queries are used to deliver the appropriate style sheet to any browser based on the medium in use. This means that any browser that supports media queries will be able to use a style sheet specified for, say, color printing on US Letter pages, or for windows wider than 1024px, where the minimum resolution is 72dpi. There’s no need to continually update your matrix of browser support, since you’re not targeting browsers. As new browsers and browser versions are released, there’ll be no need to change anything to support them—your media queries will just...work. And, as we’ve seen, we can use media queries now with browsers that already support HTML 4 media-based linking and CSS2 @media rules, even if they don’t yet support features in media queries.

The Wrap

The web’s ties to the PC and laptop are fast disappearing. It’s time to make sure your designs work in devices like high-resolution handhelds, low-resolution TVs, and other increasingly common browsing platforms. Media queries are a key tool in achieving this.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset