Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

A short introduction to CSS nesting

A short introduction to CSS nesting Photo by La-Rel Easter

I did use Sass and Less in the past, and one of my favorite features was the nesting. Not only me but the whole community was asking about that constantly over the years. The browser vendors heard that plea, and today, we have CSS nesting.

What is it

Think about the following markup:

<section>
  <p class="a">Paragraph A</p>
  <p class="b">Paragraph B</p>
</section>

Let's say we want to style the hover effect of the second paragraph. Without nesting, we'll probably do something like this:

section .b {
  color: blue;
}
section .b:hover {
  color: green;
}

With nesting, the code looks a bit easier to understand:

section {
  .b {
    color: blue;
    &:hover {
      color: green;
    }
  }
}

The nesting gives us a better idea about the scope of the styles. It is just easier to read.

The rules

There is a good documentation on MDN but here are the main points:

(1) We can nest one or more selectors inside another selector to target specific elements. The nesting is achieved by placing the nested selector(s) inside the outer selector's curly brackets.

(2) When we nest a selector, we create a relationship where the nested selector styles only apply to elements that are descendants of the outer selector.

(3) We can have multiple levels of nesting.

(4) We can nest pseudo selectors and media queries (check the next section).

(5) There is a limitation that we cannot have an element selector directly nested inside another selector. To workaround that we have to use & or > (basically any of the following special symbols & @ : . > ~ + # [ *).

Pseudo classes and media queries also work

We already saw the :hover pseudo class above. The same technique also works for stuff like :first-child:

section {
  & p {
    &:first-child {
      text-decoration: underline;
    }
  }
}

This is the same as saying:

section p:first-child {
  text-decoration: underline;
}

Another useful nesting is possible - media queries:

.a {
  color: red;
  @media all and (max-width: 1000px) {
    color: yellow;
  }
}

Compatibility

Of course, it depends on the browser matrix you are working on, but I think the compatibility of this feature is quite good.

CSS nesting comaptibility

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.