Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Sass-like nesting in native CSS

If you’re like me who finds Sass’s CSS nesting feature pretty useful, you’ll be pleased to know that the good days are coming for all of us.

So, if you’re unaware, Sass’s CSS nesting feature allows you to nest CSS selectors inside other selectors. For instance, you can write something like so.

.parent {
    .child {
        color: red;
    }
}

And this will be compiled into the following CSS.

.parent .child {
    color: red;
}

This is pretty useful when you want to write CSS for a specific element that is a child of another element. You don’t have to write the parent selector again and again. You can just nest the child selector inside the parent selector and you’re good to go.

Native CSS nesting

Now, a similar feature is coming to native CSS as well. The CSS Nesting Module is now shipped in Safari Technology Preview 162 and Chrome Dev (by enabling the “Experimental Web Platform features” flag in the browser).

Once enabled, you can write the above Sass-like code in the native CSS like so.

.parent {
    .child {
        color: red;
    }

    #childWithId {
        color: red;
    }
}

Pretty neat, right?

There are some caveats though.

Limitations

To use CSS nesting, you must nest the selectors that only start with the following symbols: ., :, [, >, +, ~, #, *. That’s because of how the browser parses the CSS. If you nest a selector that doesn’t start with any of the above symbols (such as p, span, div, etc.), the nesting will be ignored.

To get around this, you can prepend the child selector with & like so.

.parent {
    & span {
        color: red;
    }
}

The above code will be compiled into the following CSS.

.parent span {
    color: red;
}

This will also work in scenarios like the following.

ul {
  padding-left: 1em;
}

.component ul {
  padding-left: 0;
}

As you can tell, here, the ul selector is not nested inside the .component selector.

To make ul selector nested inside the .component selector, you can append & to the .component selector like so.

ul {
  padding-left: 1em;

  .component & {
    padding-left: 0;
  } 
}

And that’s pretty much it!

In closing

Since the CSS Nesting Module is still in the draft stage, it’s not recommended to use it in production yet. But it’s good to know that the feature is coming to native CSS once it’s matured enough.

Till then, you can test it out in one of the supported browsers and submit your feedback or issues at bugs.webkit.org or bugs.chromium.org.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?