Media Queries

W3C Candidate Recommendation 8 July 2002

This version:
http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708
Latest version:
http://www.w3.org/TR/css3-mediaqueries
Previous version:
http://www.w3.org/TR/2002/WD-css3-mediaqueries-20020123
Editors:
Håkon Wium Lie, Opera Software, howcome@opera.com
Tantek Çelik, Microsoft Corporation, tantekc@microsoft.com
Daniel Glazman, Netscape/AOL, glazman@netscape.com

Abstract

HTML4 and CSS2 currently support media-dependent style sheets tailored for different media types. For example, a document may use sans-serif fonts when displayed on a screen and serif fonts when printed. "Screen" and "print" are two of media types that have been defined. Media Queries extend the functionality of media types by allowing more precise labeling of style sheets.

A Media Query consists of a media type and one or more expressions to limit the scope of style sheets. Among the media features that can be used in media queries are "width", "height", and "color". By using Media Queries, presentations can be tailored to a specific range of output devices without changing the content itself.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. The latest status of this document series is maintained at the W3C.

This document is produced by the CSS Working Group (part of the Style Activity, see summary) and is one of the modules of the upcoming CSS3 specification.

The specification is being put forth as a Candidate Recommendation, which means that W3C believes this specification is stable. It can still be updated by the Working Group, but only to clarify its meaning. If, unexpectedly, serious problems are found, it will be returned to Working Draft status. Otherwise, as soon as the exit criteria are met, it will progress to become Proposed Recommendation. In either case, the duration of the Candidate Recommendation phase will be at least six months (July 2002 - Jan 2003).

For this specification to exit the CR stage, the following conditions shall be met:

  1. There must be at least two interoperable implementations. For the purposes of this criterion, we define the following terms:

    interoperable

    passing the respective test case(s) in the CSS test suite, or, if the implementation is not a web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a UA is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the specification.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipping (i.e. development, private or unofficial versions are insufficient).
    4. is not experimental (i.e. is intended for a wide audience and could be used on a daily basis.)
  2. A minimum of sixth months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

  3. The specified technology must not be harmful for accessibility.

All persons are encouraged to review and implement this specification and return comments to the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS Working Group. The comments received on the last working draft are still available.

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

A list of current W3C Recommendations and other technical documents http://www.w3.org/TR.

Table of contents

1. Background

[informative]

HTML4 [HTML401] and CSS2 [CSS2] currently support media-dependent style sheets tailored for different media types. For example, a document may use different style sheets for screen and print. In HTML4, this can be written as:

<link rel="stylesheet" type="text/css" 
  media="screen" href="sans-serif.css">
<link rel="stylesheet" type="text/css" 
  media="print" href="serif.css">

Inside a CSS style sheet, one can declare that sections apply to certain media types:

@media screen {
  * { font-family: sans-serif }
}

The "print" and "screen" media types are defined in HTML4. The complete list of media types in HTML4 is: "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv". CSS2 defines the same list with the addition of "embossed" to differentiate between braille tactile feedback devices and braille printers. Also, "all" is used to indicate that the style sheet applies to all media types.

Media-specific style sheets are supported by several user agents. The most commonly used feature is to distinguish between "screen" and "print", and "projection" is beginning to catch on.

There have been requests for ways to describe in more detail what type of output devices a style sheet applies to. Fortunately HTML4 foresaw these requests and defined a forward-compatible syntax for media types. Here is a quote from HTML4, section 6.13:

Future versions of HTML may introduce new values and may allow parameterized values. To facilitate the introduction of these extensions, conforming user agents must be able to parse the media attribute value as follows:

  1. The value is a comma-separated list of entries. For example,
    media="screen, 3d-glasses, print and resolution > 90dpi"
    

    is mapped to:

    "screen"
    "3d-glasses"
    "print and resolution > 90dpi"
    
  2. Each entry is truncated just before the first character that isn't a US ASCII letter [a-zA-Z] (Unicode decimal 65-90, 97-122), digit [0-9] (Unicode hex 30-39), or hyphen (45). In the example, this gives:
    "screen"
    "3d-glasses"
    "print"
    

The hypothetical example from the HTML4 specification is worth discussing in more detail:

<link rel="stylesheet" media="screen, 3d-glasses, 
  print and resolution > 90dpi" ... >

There are two logical operators in the example above. The comma denotes the logical OR, and the word "and" denotes the logical AND. The logical OR is already part of the HTML4 specification. The logical AND operator, however, is not defined.

Another operator used in the example above is "greater-than", denoted by ">". The square brackets and the ampersand character are reserved in HTML and XML and are therefore not suitable for use.

Finally, two different vocabularies are used: one for the media features ("resolution" is used above) and one for units (e.g. "dpi").

2. Requirements

[informative]

In order for a solution to provide useful new functionality while remaining compatible current with user agents supporting HTML4, the following requirements should be fulfilled:

  1. The syntax must fit into the media type syntax reserved in. HTML4
  2. The solution must describe, in some detail, what kind of devices a style sheet can be applied to.
  3. The syntax must be usable in future versions of CSS and XHTML.
  4. The solution must offer more expressive power than the current solution without adding significant extra costs.
  5. The solution must use a vocabulary in line with CSS and HTML.
  6. The syntax must leave room for future extensions.

[informative]

3.1. CC/PP

Within W3C the work on CC/PP (Composite Capabilities/Preference Profiles) has addressed similar issues. The goal of the CC/PP framework is to specify how client devices express their capabilities and preferences to a server. Media Queries go the other way; it's the document that declares what kind of media types a style sheet is suitable for. Still, the definition of media features could be shared between CC/PP and Media Queries.

In a Working Draft titled Composite Capability/Preference Profiles (CC/PP): Structure and Vocabularies [CCPP], a non-mandatory Appendix (CC/PP attribute vocabulary for print and display) describe five generic media features:

Name Value Description
charWidth integer the display width of a the text display device
charHeight integer the display height of a text display device
pix-x integer the display width of an image display device
pix-y integer the display height of an image display device
color binary | grey | limited | mapped | full an indication of the color capabilities of the device

The last three media features are borrowed from RFC2534 [RFC2534].

It is noteworthy that the first two media features use a different naming style (the so-called "CamelCase") than the last three.

3.2. RFC2534

Like CC/PP, RFC2534 also provides a framework for user agents to declare their capabilities. In addition to "color", "pix-x" and "pix-y" (described above) RFC2534 defines several other generic media features:

Name Value Description
ua-media screen | screen-paged | stationery | transparency | envelope | envelope-plain | continuous Indicates device type
dpi rational numbers Resolution in dots per inch
paper-size letter | a4 | b4 | a3 | legal The size of the paged output device

For several reasons, these are not directly reusable:

3.3. RFC2533

RFC2533 [RFC2533] describes a syntax that can be used to define "feature sets" which are formed from combinations and relations involving individual media features. Here is a sample feature set:

  (& (pix-x>=750) (pix-y<=500) (color=15) )

Alas, Media Queries could not use this syntax since '<', '>' and '&' characters are, in their unescaped form, illegal inside HTML attributes. In their escaped form ('&gt;', '&lt;' and '&amp') they look ugly.

However, the same expressions can be written in Media Queries using comma-separated lists (to express logical OR), the 'and' keyword (to express logical AND) and 'min'/'max' prefixes to express '>=' and '<='.

4. Media Queries

[normative]

A Media Query consists of a media type and one or more expressions involving media features. Here is a simple example written in HTML:

<link rel="stylesheet" media="screen and (color)" 
  href="http://www.example.com/color" />

The example above expresses that a certain style sheet (found from http://www.example.com/color) applies to devices of a certain media type ("screen") with certain characteristics (it must be a color screen).

The Media Query is a logical expression that is either true or false. A Media Query is true if the media type of the Media Query matches the media type of the device where the user agent is running, and all expressions in the Media Query are true. (The user agent is responsible for knowing which one of the defined media types which most closely resembles the device.) In the example above there is one expression ("(color)").

Several Media Queries can be combined in a comma-separated list. If one or more of the Media Queries in the comma-separated list is true, the associated style sheet is applied, otherwise the associated style sheet is ignored. Consider this example written in CSS:

@media screen and (color),
  projection and (color) { ... }

The comma expresses a logical OR, while the "and" keyword expresses a logical AND. There is also a logical NOT in the syntax:

<link rel="stylesheet" media="not screen and (color)" 
  href="http://www.example.com/color" />

The presence of the keyword "not" at the beginning of the query will negate the result. I.e., if the Media Query had been true without the "not" keyword it will become false, and vice versa. User agents that only support media types (as described in HTML4) will not recognize the "not" keyword and the associated style sheet is therefore not applied.

The keyword "only" can also be used to hide style sheets from older user agents:

<link rel="stylesheet" media="only screen and (color)"
  href="http://www.example.com/color" />

User agents supporting this specification will process media queries starting with "only" as if the "only" keyword was not present.

All Media Queries can be used in HTML, XHTML, XML [XMLSTYLE], and without changing their syntax. Here is the same example written in all three languages:

<?xml-stylesheet media="screen and (color), projection and (color)"
 rel="stylesheet" href="http://www.example.com/color" ?>
<link rel="stylesheet" media="screen and (color), projection and (color)"
 rel="stylesheet" href="http://www.example.com/color" />
@media screen and (color), projection and (color)
 { @import url(http://www.example.com/color) }

If a media feature does not apply to the device where the UA is running, expressions involving the media feature will be false. For example, the media feature "device-aspect-ratio" only applies to visual devices. On an aural device, expressions involving "device-aspect-ratio" will therefore always be false. Here is another example of a Media Query which is always false:

<link rel="stylesheet" media="aural and (min-device-width: 800px)" 
  href="http://www.example.com/color" />

Expressions will always be false if the unit of measurement does not apply to the device. For example, the px unit does not apply to tty devices so the following Media Query is always false:

<link rel="stylesheet" media="tty and (min-device-width: 800px)" 
  href="http://www.example.com/color" />

Note that the Media Queries in the two above examples would have been true if the keyword "not" had been added to the beginning of the Media Query.

To avoid circular dependencies, it is never necessary to apply the style sheet in order to evaluate expressions. For example, the aspect ratio of a printed document may be influenced by a style sheet, but expressions involving "device-aspect-ratio" will be based on the default aspect ratio of the user agent.

5. Syntax

[normative]

Here is a pseudo-BNF definition of Media Queries:

media_query: [only | not]? <media_type> [ and <expression> ]*
expression: ( <media_feature> [: <value>]? )
media_type: all | aural | braille | handheld | print | 
  projection | screen | tty | tv | embossed
media_feature: width | min-width | max-width 
  | height | min-height | max-height
  | device-width | min-device-width | max-device-width
  | device-height | min-device-height | max-device-height
  | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio
  | color | min-color | max-color
  | color-index | min-color-index | max-color-index
  | monochrome | min-monochrome | max-monochrome 
  | resolution | min-resolution | max-resolution
  | scan | grid

CSS style sheets are generally case-insensitive, and this is also the case for Media Queries.

The parentheses ("()") around expressions are required. A user agent conforming to this specification must not process expressions without the parentheses. By following this requirement, there will be room for future extensions in the syntax.

Expressions involving unknown media features are always false. Consider this example:

<link rel="stylesheet" media="all and (max-weight: 3kg)
  and (color)" href="http://www.example.com/color" />

Since "max-weight" is an unknown media feature, the Media Query is false and the associated style sheet will not be applied.

For a definition of values used in Media Queries, see CSS2, section 4.3: Values and Units.

6. Media features

[normative]

Syntactically, media features resemble CSS properties: they have names and accept certain values. There are, however, several important differences between properties and media features:

This specification defines media features usable with visual and tactile devices. Similarly, media features can be defined for aural media types.

6.1. width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The "width" media feature describes the width of the rendering surface of the output device. For continuous media, this is the width of the viewport (as described by CSS2). For paged media, this is the width of the page box (as described by CSS2).

For example, this Media Query expresses that the style sheet is usable on printed output wider than 25cm:

<link rel="stylesheet" media="print and (min-width: 25cm)" href="http://...." />

This Media Query expresses that the style sheet is usable on devices with viewport (the part of the screen/paper where the document is rendered) widths between 400 and 700 pixels:

@media screen and (min-width: 400px) and (max-width: 700px) { ... }

This Media Query expresses that style sheet is usable on screen and handheld devices if the width of the viewport is greater than 20em.

@media handheld and (min-width: 20em), 
  screen and (min-width: 20em) { ... }

The "em" value is based on the font size of the root element.

6.2. height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The "height" media feature describes the height of the rendering surface of the output device. For continuous media, this is the height of the viewport (as described by CSS2). For paged media, this is the width of the page box (as described by CSS2).

6.3. device-width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The "device-width" media feature describes the width of the output device.

@media screen and (device-width: 800px) { ... }

In the example above, the style sheet will apply only to screens that currently displays exactly 800 horizontal pixels. The "px" unit is of the logical kind, as described in the Units section.

6.4. device-height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The "device-height" media feature describes the height of the output device.

<link rel="stylesheet" media="screen and (device-height: 600px)" />

In the example above, the style sheet will apply only to screens that currently displays exactly 600 vertical pixels. The "px" unit is of the logical kind, as described in the Units section.

6.5. device-aspect-ratio

Value: <integer> / <integer>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The "device-aspect-ratio" media feature describes the aspect ratio of the output device. The value consists of two positive integers separated by a "/".

In this specification, aspect ratio is defined as the number of horizontal pixels over the number of vertical pixels.

For example, if a screen device has 1280 horizontal pixels and 720 vertical pixels (commonly referred to as "16:9"), the following Media Queries will all match the device:

@media screen and (device-aspect-ratio: 16/9) { ... }
@media screen and (device-aspect-ratio: 32/18) { ... }
@media screen and (device-aspect-ratio: 1280/720) { ... }
@media screen and (device-aspect-ratio: 2560/1440) { ... }

Note that determining if a specified aspect ratio matches the device aspect ratio can be done through multiplication (e.g., 1280*9 = 11520 = 720*16) to avoid floating point operations.

Using prefixes, portrait and landscape aspect ratios can be expressed:

@media screen and (max-device-ratio: 1/1) /* portrait or square */
@media screen and (min-device-ratio: 1/1) /* landscape or square */

6.6. color

Value: <integer>
Applies to: visual media types
Accept min/max prefixes: yes

The "color" media feature describes the number of bits per color component of the output device. If the device is not a color device, the value will be 0. For example, these two Media Queries express that a style sheet applies to all color devices:

@media all and (color) { ... }
@media all and (min-color: 1) { ... }

This Media Query expresses that a style sheet applies to color devices with 2 or more bits per color component:

@media all and (min-color: 2) { ... }

For instance, if an 8-bit color system represents the red component with 3 bits, the green component with 3 bits and the blue component with 2 bits, the "color" media feature will have a value of 2.

In a device with indexed colors, the "color" media feature will hold the minimum number of bits per color component in the lookup table.

The described functionality is only able to describe color capabilities at a superficial level. If further functionality is required, RFC2531 [RFC2531] provides more specific media features which may be supported at a later stage.

6.7. color-index

Value: <integer>
Applies to: visual media types
Accepts min/max prefixes: yes

The "color-index" media feature describes the number of entries in the color lookup table of the output device. For example, here are two ways to express that a style sheet applies to all color index devices:

@media all and (color-index) { ... }
@media all and (min-color-index: 1) { ... }

This Media Query expresses that a style sheet applies to a color index device with 256 or more entries:

<?xml-stylesheet media="all and (min-color-index: 256)" 
  href="http://www.example.com/..." ?>

6.8. monochrome

Value: <integer>
Applies to: visual media types
Accepts prefixes: yes

The "monochrome" media feature describes the number of bits per pixel in a monochrome frame buffer. If the device is not a monochrome device, the output device value will be 0. For example, here are two ways to express that a style sheet applies to all monochrome devices:

@media all and (monochrome) { ... }
@media all and (min-monochrome: 1) { ... }

For example, express that a style sheet applies to monochrome devices with more than 2 bits per pixels:

@media all and (min-monochrome: 2) { ... }

Express that there is one style sheet for color pages and another for monochrome:

<link rel="stylesheet" media="print and (color)" 
  href="http://..." />
<link rel="stylesheet" media="print and (monochrome)" 
  href="http://..." />

6.9. resolution

Value: <resolution>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The "resolution" media feature describes the resolution of the output device, i.e. the density of the pixels.

For example, this Media Query expresses that a style sheet is usable on devices with resolution greater than 300 dots per inch:

@media print and (min-resolution: 300dpi) { ... }

6.10. scan

Value: progressive | interlace
Applies to: tv media types
Accepts min/max prefixes: no

The "scan" media feature describes the scanning process of tv output devices.

For example, this Media Query expresses that a style sheet is usable on tv devices with progressive scanning:

@media tv and (scan: progressive) { ... }

6.11. grid

Value: <integer>
Applies to: all media types
Accepts min/max prefixes: no

The "grid" media feature is used to query whether the output device is grid or bitmap. If the output device is grid-based (e.g., a tty terminal, or a phone display with only one fixed font), the value will be 1. Otherwise, the value will be 0.

The "em" unit has a special meaning in grid output devices. Since the exact with of an "em" cannot be determined, one "em" is assumed to be the width of one grid cell horizontally and the height of one grid cell vertically.

Here are two examples:

@media handheld and (grid) and (max-width: 15em) { ... }
@media handheld and (grid) and (device-max-height: 7em) { ... }

7. Units

[normative]

The pixel unit used in Media Queries are of the "logical" kind (which is reported to the user agent) rather than the "physical" kind (which often remains unknown to the user agent). In any case, the user agent must use the same definition of a pixel in Media Queries as is used to interpret style sheets.

Relative units in Media Queries are based on the initial values of the document's root element.

The "dpi" and "dpcm" units describe the resolution of an output device, i.e. the density of the pixels. in "dots per inch" and "dots per centimeter", respectively. These units are only used in the "resolution" media feature.

8. Acknowledgements

[informative]

This specification is the product of the W3C Working Group on Cascading Style Sheets.

9. Appendix A. Normative references

[CSS2]
Bert Bos; Håkon Wium Lie; Chris Lilley; Ian Jacobs. Cascading Style Sheets, level 2. 1998. W3C Recommendation. URL: http://www.w3.org/TR/REC-CSS2
[HTML401]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.01 Specification. Dec 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[XMLSTYLE]
J. Clark. Associating Style Sheets with XML documents. 29 June 1999. W3C Recommendation. URL: http://www.w3.org/TR/xml-stylesheet

10. Appendix B. Informative references

[CCPP]
G. Klyne; F. Reynolds; C. Woodrow; H. Ohto (eds.). Composite Capability/Preference Profiles (CC/PP): Structure and Vocabularies. 15 March 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-CCPP-struct-vocab-20010315
[RFC2533]
G. Klyne. A Syntax for Describing Media Feature Sets. March 1999. Internet RFC 2533. URL: http://www.ietf.org/rfc/rfc2533
[RFC2534]
L. Masinter; D. Wing; A. Mutz; K. Holtman. Media Features for Display, Print, and Fax. March 1999. Internet RFC 2534. URL: http://www.ietf.org/rfc/rfc2534