本文介绍了嵌套CSS @supports和@media查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试找出是否可以嵌套CSS功能查询(也称为"CSS @supports")和常规媒体查询,以及这样做的正确方法是什么.

I have been trying to figure out whether it's possible to nest CSS feature queries (also known as "CSS @supports") and regular media queries, and what would be the correct way to do it.

示例A 显示媒体查询中的功能查询.
示例B 功能查询中显示了媒体查询.

Example A shows the feature query inside the media query.
Example B shows the media query inside the feature query.

甚至有可能将它们嵌套吗?如果是这样,是否有首选的嵌套样式?是A还是B?

Is it even possible to nest them at all? If so, is there a preferred nesting style? A or B?

.foo {
    background: red;
}

/* EXAMPLE A */
@media (min-width: 50em) {
    .foo {
        background: green;
    }

    @supports (flex-wrap: wrap) {
        .foo {
            background: blue;
        }
    }
}

/* EXAMPLE B */
@supports (flex-wrap: wrap) {
    .foo {
        background: green;
    }

    @media (min-width: 50em) {
        .foo {
            background: blue;
        }
    }
}

推荐答案

根据规范的第3部分,目前,它们似乎一直被理解@supports规则和嵌套@media规则().

Both examples are valid CSS according to section 3 of the spec, and for the time being they seem to be consistently supported by browsers that understand both @supports rules and nested @media rules (also new to CSS3).

尽管这两个示例仅在同时满足 @supports的条件时才应用background: blue声明,

Although both examples will only apply the background: blue declaration when both the @media and @supports conditions are met,

  • 只有在满足(min-width: 50em)媒体查询的情况下,A才会应用background: greenbackground: blue
  • B仅当浏览器理解@supports并且支持flex-wrap: wrap时,才会应用这两种声明.
  • A will apply either background: green or background: blue if and only if the (min-width: 50em) media query is met;
  • B will apply either declaration if and only if the browser understands @supports and supports flex-wrap: wrap.

由于您的两个示例含义不同,所以选择哪种取决于您的用例:

Since your two examples mean subtly different things, which one you choose will depend on your use case:

  • 如果您不希望不支持@supportsflex-wrap: wrap的浏览器看到 声明,而是始终应用​​background: red,请选择B.
  • 否则,如果您希望任何浏览器(无论如何都能理解媒体查询)在指定的视口宽度上应用background: green,即使由于不支持@supportsflex-wrap: wrap而永远不会应用background: blue时,请选择答:
  • If you do not want browsers that don't support @supports or flex-wrap: wrap to see either declaration, and to instead always apply background: red, choose B.
  • Otherwise, if you want any browser (that understands media queries anyway) to apply background: green at the specified viewport width, even if it will never apply background: blue due to not supporting @supports or flex-wrap: wrap, choose A.

这篇关于嵌套CSS @supports和@media查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 08:07