Codeskill

Learn to code, step by step

Nesting in SCSS: Hierarchical Magic

Nesting in SCSS. Writing selectors inside other selectors so your CSS matches your HTML structure.

Understanding nesting in SCSS

Nesting lets you write CSS selectors inside other selectors. It mirrors the nested structure of HTML and keeps related styles grouped together.

Basic nesting

Consider this HTML:

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <!-- More list items -->
  </ul>
</nav>

In plain CSS, you might write:

nav ul {
  list-style: none;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  text-decoration: none;
}

In SCSS, you can nest those selectors:

nav {
  ul {
    list-style: none;

    li {
      display: inline-block;

      a {
        text-decoration: none;
      }
    }
  }
}

The SCSS version follows the HTML structure, which makes it easier to read and update.

The ampersand (&)

The ampersand (&) refers to the parent selector. It is useful for pseudo-classes, pseudo-elements, and BEM naming.

For instance:

.button {
  background: blue;
  color: white;
  &:hover {
    background: darken(blue, 10%);
  }
  &__icon {
    margin-right: 5px;
  }
}

&:hover compiles to .button:hover. &__icon follows BEM convention and compiles to .button__icon.

Nesting properties

SCSS also lets you nest properties that share a namespace – useful for font-*, margin-*, and border-* properties.

Example:

.widget {
  font: {
    family: Arial, sans-serif;
    size: 1em;
    weight: bold;
  }
  margin: {
    top: 10px;
    bottom: 20px;
  }
}

This compiles to individual font-family, font-size, font-weight, margin-top, and margin-bottom properties.

Caution: over-nesting

Nesting is useful, but going too deep creates overly specific CSS that is hard to override. A good rule of thumb: avoid nesting more than three levels. If you are going deeper, consider splitting styles into mixins or separate selectors.

Using nesting with variables and mixins

Nesting works well with variables and mixins:

$primary-color: #3498db;

.navigation {
  background: $primary-color;

  ul {
    list-style: none;

    li {
      display: inline-block;

      @include hover-effect; // Calling a mixin
    }
  }
}

Here, $primary-color and the hover-effect mixin are used inside nested selectors.

Nesting and media queries

You can nest media queries inside selectors, keeping responsive styles next to the base styles they modify:

.sidebar {
  width: 300px;

  @media (max-width: 600px) {
    width: 100%;
  }
}

The media query sits inside .sidebar, so it is obvious which element it affects.

Organising your styles with nesting

Used sensibly, nesting keeps related styles together and mirrors your HTML. That makes stylesheets easier to navigate – just do not overdo the depth.

PreviousVariables in SCSS: Dynamic Styling Made Easy