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:
- For the screen and projection media types, text will be dark grey and the background will consist of a repeated image.
- For the print media type, text will be black on white.
- User agents that apply the handheld media type will render dark green text on a white background.
- For all other media types, text will be dark grey on white.
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.
- Previous post: Remember the Authoring Tool Accessibility Guidelines (ATAG)
- Next post: Reverse chronological order comments