Search code examples
cssmedia-queries

What exactly does the 'only' keyword do in CSS media queries?


On Mozilla's page about media queries, it says:

The only keyword hides style sheets from older browsers that don't support media queries:

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

However, further down the page it also says,

Media queries involving unknown media types are always false.

So how can a browser not supporting media queries show the stylesheet when it's set to screen and (color)? It wouldn't understand and color so shouldn't show it? And if Mozilla is referring to browsers with literally zero support for the media attribute, why would adding only stop them from showing the stylesheet?

Can anyone explain the process by which older browsers parse (or don't) the media attribute?


Solution

  • If unknown media queries are always false, why does screen and (color) show the stylesheet but only screen and (color) not?

    Previously the media attribute was used for media types, rather than media queries. The spec has since extended the use of this attribute to also support media queries.

    An older browser would expect to see a media type (e.g. screen, print, etc.), and wouldn't support a media query (e.g. screen and (color) and (min-device-width: 800px)).

    Without the "only", an older browser is allowed to interpret screen and (color) as being the screen media type. Prefixing it with only prevents this from happening.

    Can anyone explain the process by which older browsers parse (or don't) the media attribute?

    The browser knows whether it supports a particular doctype or not, which is part of the HTML document you send. If the doctype is one that permits media queries, then a conforming browser will either handle it (because it conforms) or ignore it (because it doesn't know how to handle that doctype, and makes a best-case effort).

    As you suspected, implementations that don't understand it typically don't parse it. Browsers are expected to follow the robustness principle:

    Be liberal in what you accept, and conservative in what you send.

    Rather than erroring out or doing something obtrusive or unusual, the default is to pretend that the unknown element doesn't exist at all.

    Similarly, you probaly wouldn't experience any ill effects if you write a link that has a strange attribute, like:

    <a href="http://google.com" unknown-attribute="foobar">Google</a>