Saving a HTTP request by combining screen and print styles
April 19, 2009
Minimizing HTTP requests is a very effective way for speeding up your website. In his book “High Performance Web Sites”, Steve Souders talks about this practice as the number one rule to front-end optimization.
Some well-known techniques to reduce HTTP requests include using CSS sprites and combining multiple scripts and stylesheets into single files. Ideally you should be using only one stylesheet. However, how many times have you seen the following two lines in the <head> of a HTML page?
<link rel="stylesheet" type="text/css" href="screen.css" media="screen" />
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
Combining screen and print styles
I get the impression many people are unaware of the fact you can combine screen and print styles into a single stylesheet. Actually you can combine all media types, and it is easy to do.
Linking to your stylesheet
<link rel="stylesheet" type="text/css" href="styles.css" media="screen, print" />
You may be wondering why I did not use media="all" or simply omitted the media attribute. By stating the media types the stylesheet applies to right there in the <link>, user agents may decide not to load the stylesheet at all if it does not apply to the current device. Another possible HTTP request less.
Splitting up your stylesheet
All that is left to do is telling the browser which parts of styles.css apply to screen and which parts apply to print. The example below is self-explanatory.
@media screen {
body { font-size:14px; }
}
@media print {
body { font-size:10pt; }
h1, h2, h3 { page-break-after:avoid; }
}
Styles that apply to both screen and print do not need not be wrapped in an @media rule in this case since the stylesheet itself applies to both media types already, as specified in the <link>. Just for the sake of completeness, though, note that you can specify multiple media types separated by commas.
@media screen, print {
body { line-height:1.4; }
}
To freshen up your knowledge about @media rules, I recommend you have a look at the CSS specification for media types.