Codeskill

Learn to code, step by step

Nesting in SASS: Bringing Order to CSS Chaos

Nesting in SASS – a way to write CSS selectors in a hierarchy that matches your HTML. If you have ever untangled long selector chains like nav ul li a, nesting is worth knowing about.

Understanding nesting in SASS

If you have done any programming, nesting will feel familiar. In SASS, you write child selectors inside a parent selector. The result mirrors your HTML markup and keeps related styles grouped together.

Styling a navigation bar in plain CSS might look like this:

nav {
  background-color: #333;
}
nav ul {
  list-style: none;
}
nav ul li {
  display: inline-block;
}
nav ul li a {
  color: white;
}

In SASS, the same thing nests neatly:

nav {
  background-color: #333;
  ul {
    list-style: none;
    li {
      display: inline-block;
      a {
        color: white;
      }
    }
  }
}

The SASS version follows the HTML structure, which makes it easier to read and maintain.

Benefits of nesting

  1. Improved readability: The hierarchy matches your DOM structure.
  2. Easier maintenance: When HTML changes, you can update the CSS structure to match without hunting for scattered selectors.
  3. More organised code: Related styles stay together instead of spread across the file.

Avoiding the pitfalls

Nesting is useful, but do not overdo it. Deep nesting produces long, overly specific selectors that are hard to override. A good rule of thumb: avoid going more than three levels deep. That keeps the compiled CSS efficient and reduces specificity headaches.

Advanced nesting: pseudo-classes and media queries

Nesting works with pseudo-classes and media queries too:

.button {
  background-color: blue;
  &:hover {
    background-color: darkblue;
  }
  @media (min-width: 500px) {
    padding: 10px 20px;
  }
}

The & symbol references the parent selector, which makes pseudo-classes straightforward. The media query sits inside the selector, so all button-related styles stay in one place.

Nesting is one of the features that makes SASS feel like a natural extension of CSS. Use it to keep stylesheets readable, but keep the depth sensible.

PreviousEmbracing Variables in SASS: A Game-Changer for Stylesheets