Sass Quick Tip: Keeping Specificity Low using @at-root

Sass Quick Tip: Keeping Specificity Low using @at-root

December 7, 2015

Nesting your rule sets in Sass is an easier way to write CSS, not too mention it keeps it clean and organized. The problem of over-nesting leads to overly-specific CSS selectors that make it difficult to override later.

For instance, let’s look at this markup:

<header>
  <nav class="primary-nav">
    <a href="#">About</a>
    <a href="#">Archive</a>
  </nav>
</header>

It makes sense to write all rule sets nested inside the parent, header {}.

header {
  .primary-nav {
    color: blue;
  }
}

This makes sense from an organizational stand-point. Rule sets that affect the header are nested inside of it. However, the nav element already has a very specific class, primary-nav. So there’s no need to nest it inside of the header except it keeps the code organized. But its definately more specific than it needs to be as it will compile in to:

header .primary-nav { color: blue; }

@at-root

@at-root to the rescue.

header {
  @at-root .primary-nav {
    color: blue;
  }
}

This compiles in to the following:

.primary-nav { color: blue; }

Way better because its only as specific as it needs to be. @at-root treats nested selectors like they were never nested at all.

Something like this:

.grand-parent {
  .parent {
    @at-root .child { color: blue; }
  }
}

Compiles down to this:

.child { color: blue; }

What I like about @at-root is that it allows you to over-nest for the sake of organization, but without the added specificity.

Mastering CSS: Book by Rich Finelli
Mastering CSS, the Book! Flexbox, Layout, Animations, Responsive, Retina, and more!
Mastering CSS, 2nd Edition, video course by Rich Finelli
Mastering CSS, Second Edition: 47 videos on how to make websites like a boss! Flexbox, Animations, Responsive, Retina, and more!
Back to top