-3

In stylesheets, the majority of CSS rules (NOT talking about SASS or LESS here) are structured like this:

selector {
    property_1 : value_1;
    .
    .
    .
    property_n : value_n;
}

There is only 1 {} block attached to the selector (with no sub {} blocks inside). Call this degree of nesting = 1.

With at-rules though, we see rules such as this:

@media screen and (min-width:1000px) {

    body {
        font-size: 20px;  
    }

}

There is clearly a nested CSS block inside the @media rule, so degree of nesting = 2

The highest I can imagine is something that has a nesting degree = 3 such as this:

@media screen and (min-width:1000px) {
    
    @keyframes myidentifier {

        0%   { top: 0; left: 0; }
        100% { top: 100px; left: 100%; }

    }

}

Is it possible to nest CSS blocks any deeper than this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356

2 Answers2

3

Conditional CSS Rules can be nested as deeply as you desire:

@media print {
  @media (max-width: 12cm) {
    /* ... */
  }
}
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • No problem. I would recommend reading the W3 docs on [Conditional Rules](http://www.w3.org/TR/css3-conditional/#at-media) if you want to learn more. – jeffjenx Apr 21 '16 at 15:02
  • I'm glad this can be freely relied on today. At the time this was posted, I believe implementations were still slowly creeping in. Also check out (specifically for at-media rules) https://stackoverflow.com/questions/11746581/nesting-media-rules-in-css/11747166#11747166 – BoltClock Apr 29 '21 at 12:04
0

To expand on Jeff's answer:

Style rules (previously called rulesets) — that is, rules with selectors and property-value declarations — cannot be nested in standard CSS. There is a proposed specification called css-nesting that aims to bring this ability from popular stylesheet preprocessors to standard CSS, but it's not yet set in stone.

Conditional at-rules, such as @media and @supports, may be nested within one another as much as you like. You can even nest one within the other. Previously, in CSS2.1, @media at-rules could not be nested, but this restriction has been removed in css-conditional-3, which contains a section explaining how nesting of conditional rules works.

This does not apply to all at-rules that have a block, though. For example, @keyframes at-rules aren't conditional rules; these may appear within @media or @supports rules to any nesting depth, but cannot themselves contain conditional rules, or indeed other @keyframes rules. They may only contain keyframe blocks, such as the 0% and 100% blocks in your example.

As more modules are added to CSS, new at-rules may be added that have their own nesting restrictions defined in their respective specifications. However, anything defined in css-conditional-3 can be nested interchangeably and to any depth.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356