CSS efficiency tip: use a single stylesheet file for multiple media

The way most people link CSS intended for different media types, such as screen, print, or handheld, is to use multiple files. The files are then linked either through link elements with a media attribute or through @import statements with one or more media types specified.

There is nothing wrong with splitting your CSS into multiple files and linking them this way (I currently do that here on this site), but there are two drawbacks: it leads to more HTTP requests from the browser to the server and the need to maintain multiple CSS files.

Some people like splitting their CSS across several files, and not only for different media but for different sections of a site. I have tried working like that and while it may work well for some, it most definitely does not suit my workflow. To each his own, but the fewer CSS files I have to keep track of, the faster I work.

Luckily for me and others who feel the same way there is a way to put all of your CSS into a single file.

Enter the @media at-rule

An @media rule lets you group CSS rules by media type in the same file. Any rules outside @media rules apply to all media type that the stylesheet itself applies to.

Here is an example stylesheet that uses @media rules:

body {
	color:#444;
	background-color:#fff;
}
@media screen, projection {
	body { background-image:url(background.png); }
}
@media print {
	body { color:#000; }
}
@media handheld {
	body { color:#0f6517; }
}

Assuming that the above rules are in a CSS file that applies to all media, the following will apply:

This may or may not work for you, but personally I’ve found that doing this leads to less redundancy and reduces the risk of one or more media types being overlooked when I make changes to the CSS.

Posted on February 22, 2010 in CSS