40

Some time ago I saw an example of a css file, where the css rules/selectors where specified in a nested way, e.g. something like this:

div.a {
  color: red;
  div.b {
    font-weight: bold;
  }
}

I'm not sure where I saw that (probably in a SO question), or whether it was exactly as shown above.

My questions: Is the above CSS correct/valid? Is it a standard way to specify CSS rules or is this a browser-dependent hack?

0

4 Answers 4

48

That is not valid standard CSS, but it's an example of nesting class declarations using Sass/SCSS or LESS and I believe other CSS extensions out there, which expand it to something like this (which is valid CSS), before serving it to the browser to use:

div.a {
  color: red;
}

div.a div.b {
  /* Inherits color from div.a */
  font-weight: bold;
}
5

What you are probably referring to is LESS.

The example, you gave is not valid CSS, but is valid with LESS. LESS will "compile" the nested CSS and convert it to something which is valid CSS.

2

You can nest rules with SASS, http://sass-lang.com/

Maybe that was it?

1
  • It should be noted that the output from SASS is still CSS compliant, without nesting. SASS nesting just makes it easier to write.
    – Robert
    Sep 15, 2010 at 19:03
1

Seems there is a proposal over at https://tabatkins.github.io/specs/css-nesting/

but I can't find the status of it

2
  • now (February 2023) it is a working draft: w3.org/TR/css-nesting-1; "can i use" says chrome will support it on the next version (112): caniuse.com/css-nesting
    – Tilt
    Mar 30, 2023 at 13:06
  • Many browsers support nesting with & now (Sept. 2023), but only in their latest versions or in development mode. Check all the details in the Mozilla page Sep 9, 2023 at 12:38

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