The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Media Queries 19

Problems arose because some early adopters of media queries would, for
example, apply large background images to elements and then write rules
to hide them from mobile devices:

E { background-image: url('huge-image.jpg'); }
@media (max-width: 600px) {
E { display: none; }
}

But those background images, despite being hidden, were still down-
loaded by the browser and held in the cache even though they weren’t dis-
played. This method increases the page’s load time and consumes bandwidth
allowances—neither of which is good for mobile device users without wire-
less connections.
The mobile-first way to create your pages is to first make a basic style
sheet, which is applied to all browsers, including mobile, and to then pro-
gressively add assets and features for users with larger screens, loaded using
a media query with the min-width feature:

@media (min-width: 600px) {
E { background-image: url('huge-image.jpg'); }
}

This change means the background image in question never gets
loaded on devices with smaller screens. This approach can be extrapolated
to loading entire style sheets:

<link href="basic.css" rel="stylesheet">
<link href="desktop.css" rel="stylesheet" media="(min-width: 600px)">

When the style sheets are separated in this way, some browsers will
optimize the way the style sheets are loaded; in Chrome, for example, as
the file desktop.css doesn’t apply to devices with a screen width of less than
600px, its loading is delayed until after more high-priority assets have been
downloaded—a quite useful optimization.
This mobile-first approach works for the great majority of browsers
from the past few years; any really old browsers will get the basic style sheet
instead, which is probably better for them as they won’t be able to cope with
the advanced features I’ll be teaching you throughout the rest of this book.

Summary


Their syntax may be simple, but media queries have the capacity to be
extraordinarily powerful. With the mobile web explosion of recent years,
designers and developers are beginning to realize they have the power to
tailor their content to the user without employing the old techniques of
browser sniffing or separate (and completely different) mobile versions of
their sites.
Free download pdf