O'Reilly logo

CSS Pocket Reference, 4th Edition by Eric A. Meyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Media Queries

With media queries, an author can define the media environment in which a given style sheet is used by the browser. In the past, this was handled by setting media types with the media attribute on link elements or the media descriptor on @import declarations. Media queries take this concept several steps further by allowing authors to choose style sheets based on the features of a given media type.

Basic Concepts

The placement of media queries will be very familiar to any author who has ever set a media type. Here are two ways of applying an external style sheet when rendering the document on a color printer:

<link href="print-color.css" type="text/css" 
   media="print and (color)" rel="stylesheet">

@import url(print-color.css) print and (color);

Anywhere a media type can be used, a media query can be used. This means that it is possible to list more than one query in a comma-separated list:

<link href="print-color.css" type="text/css"
   media="print and (color), projection and (color)" 
   rel="stylesheet">

@import url(print-color.css) print and (color), 
   projection and (color);

In any situation where one of the media queries evaluates to “true,” the associated style sheet is applied. Thus, given the previous @import, print-color.css will be applied if rendering to a color printer or a color projection environment. If printing on a black-and-white printer, both queries will evaluate to “false” and print-color.css will not be applied to the document. The same holds for any screen ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required