What is the difference between “screen” and “only screen” in media queries?

后端 未结 5 1747
栀梦
栀梦 2020-11-22 14:33

What is the difference between screen and only screen in media queries?



        
5条回答
  •  有刺的猬
    2020-11-22 15:09

    The following is from Adobe docs.


    The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

    media="only screen and (min-width: 401px) and (max-width: 600px)"
    

    Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

    media="only"
    

    Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

    media="screen and (min-width: 401px) and (max-width: 600px)"
    

    as

    media="screen"
    

    In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

    Unfortunately, IE 6–8 failed to implement the specification correctly.

    Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

    In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


    So, using

    media="only screen and (min-width: 401px)"
    

    and

    media="screen and (min-width: 401px)"
    

    will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

    Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

    I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

    media="only screen and (min-width: 401px)" 
    

    as opposed to

    media="screen and (min-width: 401px)"
    

    to make sure it is not interpreted as

    media="screen"
    

    It would be a good test for someone with access to a device lab.

提交回复
热议问题