HTML and CSS Reference
When you attach a CSS file to an HTML document through the LINK element, you also have the
option of selecting the medium where the style will be applied. You indicate the medium through the
media attribute. If no media attribute is specified, then browsers understand that the same CSS file
should be used in any possible scenario.
In the beginning, the role of the media attribute was limited to using different CSS files for viewing
and printing a given HTML page. Originally, feasible values for the media attribute were screen, print ,
and all .
More recent browsers support a true query language in the media attribute that allows you to
select the CSS file to apply it to based on the browser's runtime conditions.
Dynamic selection of the CSS file
Here's an example of how to dynamically link CSS files to an HTML page using media queries.
The idea is that a page offers a number of choices and the browser dynamically picks up the most
appropriate choice given its current status.
media="only screen and (max-width: 320px)">
media="only screen and (min-width: 321px)">
Interestingly, modern browsers are also able to adjust their selection of the CSS file as dynamic
conditions change. With reference to the above code snippet, it means that the browser will
automatically apply tiny.css when the width of the screen is up to 320 pixels and switch to large.css
when the window is resized to at least 321 pixels.
The media queries mechanism serves two purposes. On one hand it gives you a chance to make
pages that adapt to the current screen size; on the other hand, it represents a simple, but effective,
tool to give your pages a mobile interface at nearly no cost. In the simplest case, in fact, a mobile
device is just a browser with a smaller screen size.
Syntax of Media Queries
As mentioned previously, a browser's runtime conditions can affect the selection of the CSS file. Let's
briefly review which runtime information you have access to in order to decide about the CSS file.
First and foremost, a media query expression begins as a way to force older browsers to ignore the
statement. Table 3-3 lists the main media query properties.