Beginning XHTML | 9 | WebReference

Beginning XHTML | 9

To page 1current pageTo page 3
[previous] [next]

Beginning XHTML

Using the '@media' Rules

The third mechanism for associating style sheets with media types is to use the @media rules. This specifies the target media types for a set of style sheet rules. For example, if you write:

@media screen {
 h1 { font-size: 18pt }
}
@media print {
 h1 { font-size: 10pt }
}
@media screen, print {
 h1 { text-align: center }
}

...you are indicating that first level header has an 18-point font when displayed on the screen, a 10-point font when printed, and center-aligned on both media types. The third of the @media rules above points out that @media rules may apply to more than one media type. In this case, media types are separated by a comma.

Note that @media rules are applied in the order in which they are processed. In other words, if two applicable @media rules define different styles for the same element or selector, the latter @media rule will apply. For example, if we wrote:

@media print {
 h1 { font-size: 10pt }
}
@media screen, print {
 h1 { font-size: 18pt; text-align: center }
}

an 18pt font will be used when displaying on the screen and when printing. With @media rules, you can specify media-dependencies within an internal style sheet or with an external style sheet.

Using '@media' Rules Within an XHTML Document

In order to specify media dependencies within an internal style sheet, you simply include the above information within your document by use of the <style> element:

<head>
  ...
  <style type="text/css">
  <!--
   @media screen {
    h1 { font-size: 18pt }
   }
   @media print {
    h1 { font-size: 10pt }
   }
   @media screen, print {
    h1 { text-align: center }
   }
  -->
  </style>
 ...
</head>

In this example, the <style> element's content is three @media rules. The first @media rule applies to the screen media type, the second to the print media type, and the third to both screen and print media types. The benefit of this approach is that common styles (such as center-alignment in the example above) can be collected under one @media rule to reduce redundancy and improve maintainability of the style information. The greatest benefit, however, of using @media rules is when they are used in external style sheets.

To page 1current pageTo page 3
[previous] [next]


Created: April 4, 2001
Revised: April 4, 2001

URL: http://webreference.com/authoring/languages/xhtml/beginning/chap13/2/