Sass nesting, ‘&’ and @at-root

Igor Veyner
Nerd For Tech
Published in
3 min readJul 16, 2021

Building off my last post on Sass, let’s talk a bit more about nesting. I’ll be using the .scss file type but this also applies to sass files. In regular CSS you write your styling like so:

Sass allows you to nest your styling and selectors to keep your code organized and cleaner. Nobody likes scrolling up and down multiple files right?

Updating one of my projects these last few weeks I notices that this nested syntax also has the added benefit of allowing you to get better readability with your selectors. Sometimes they can get a bit out of hand in CSS.

regular CSS
Scss version

Parent Selector: &

If you’re new to Sass you might be wondering what that `&` selector is or does. It’s referred to as the Parent Selector or the Ampersand. You can use it inside of your nested styles to select the direct parent of the selector you are targeting. I’ve found it incredibly useful for Pseudo Classes like hover and focus.

Most of the time you see the Parent Selector on the left side of a selector but you can also use it after another selector to the right. This allows you to have finer control of your styles while keeping it all organized!

After processing it becomes this CSS:

@at-root rule

If you ever find yourself deeply nested and want to reference the original root selector use the @at-root rule!

You might be wondering why would you need to do this? You could just do the styling in the original context right?

My answer would be yes, exactly. In this case you wouldn’t need it at all.

The @at-root is more commonly used with the optional (with: ) or (without: ) media query features to get finer control of whatever styles you want. That might be a confusing and vague definition if you’re not familiar with the topic but so lets save that for another day.

--

--

Igor Veyner
Nerd For Tech

Senior Software Engineer @ ASAPP | Bootcamp Grad