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:

  1. body {
  2. color:#444;
  3. background-color:#fff;
  4. }
  5. @media screen, projection {
  6. body { background-image:url(background.png); }
  7. }
  8. @media print {
  9. body { color:#000; }
  10. }
  11. @media handheld {
  12. body { color:#0f6517; }
  13. }

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.

Posted on February 22, 2010 in CSS

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.