28

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.

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

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
  • nesting media queries seems to be allowerd in css3. So I assume, feature queries may work as well. But getting cross browser compatiblity is another story. Commented Feb 24, 2017 at 12:00
  • @BoltClock Thank you! At least I know now that we'll possibly get this in the future. I guess I'm back to testing browser support like it's 1999.
    – oelna
    Commented Feb 24, 2017 at 12:01
  • Scratch that, browser support seems to be just fine if you're only interested in browsers that support @supports. I'll post an answer.
    – BoltClock
    Commented Feb 24, 2017 at 12:01

1 Answer 1

25

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).

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

  • 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:

  • 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.
1
  • Dreamweaver validates only supports inside media, but not media inside supports, but its validator is not always good.
    – Iggy
    Commented May 22, 2021 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.