Chapter 20. Media-Dependent Styles

A great deal of our CSS work goes into putting content onto screens of various kinds, whether they sit on office desks or rest in the palms of our hands. There is more to the web than screens, though, and even in the part that is screen-centric, there are many different kinds of screens, each with its own constraints. Recognizing this reality, CSS provides a number of tools with which to apply styles in specific media, or in media with specific features.

Defining Media-Dependent Styles

Thanks to the mechanisms defined in HTML and CSS called media queries, you can restrict any kind of style sheet to a specific medium, such as screen or print, and set of media conditions. These mechanisms allows you to define a combination of media types and parameters such as display size or color depth, to pick two examples. We’ll cover the basic form of these queries before exploring the more complex forms.

Basic Media Queries

For HTML-based style sheets, you can impose medium restrictions through the media attribute. This works the same for both the link and style elements:

<link rel="stylesheet" type="text/css" media="print"
    href="article-print.css">
<style type="text/css" media="speech">
    body {font-family: sans-serif;}
</style>

The media attribute can accept a single medium value or a comma-separated list of values. Thus, to link in a style sheet that should be used in only the screen and speech media, you would write:

<link rel="stylesheet" type="text/css" ...

Get CSS: The Definitive Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.