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

前端 未结 2 1271
旧时难觅i
旧时难觅i 2020-12-30 06:29

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

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

相关标签:
2条回答
  • 2020-12-30 06:56

    My guess is that certain pre-CSS3 browsers, which understand only media types, interpret

    media="screen and (color)"
    media="screen" // `screen` is a known media type; ACCEPT for screen media
    

    and

    media="only screen and (color)"
    media="only"    // `only` is an unknown media type
    media="unknown" // REJECT for any media
    

    Essentially they ignore everything after the first space but treat the remainder as valid.

    0 讨论(0)
  • 2020-12-30 07:07

    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>
    
    0 讨论(0)
提交回复
热议问题