The @at-root rule in SassScript emits everything within it at the root of the document.
@at-root is generally used for advanced nesting where the normal nesting won’t work or would require a lot more code.
One example of advanced nesting is when you want to keep same style for different html tags with a specific class (inner selector) within a container (outer selector).
You can do so by nesting parent selector and selector functions. The example in this post is an example for the same.
Syntax
@at-root {
...
}
Example
@use "sass:selector";
@mixin adv-nest($inner) {
@at-root #{selector.unify(&, $inner)} {
@content;
}
}
.outer .form-el {
@include adv-nest("input") {
/* styles */
}
@include adv-nest("select") {
/* styles */
}
}
The code above will be compiled into this CSS:
.outer input.form-el {
/* styles */
}
.outer select.form-el {
/* styles */
}
Let’s understand the SCSS code.
First of all we’re importing selector built-in module from Sass and then using selector.unify() function inside a mixin to combine & with a user’s selector.
Sass will automatically add the outer selector to the inner selector but @at-root tells Sass not to include the outer selector.
Without @at-root rule, you’ll get both inner and outer selectors combined in your CSS which can be achieved using a normal nesting easily but that’s not our goal.
advanced at-root nested sass