Yogesh Chauhan's Blog

Advanced nesting in Sass (SCSS) using at-root

in SCSS on July 19, 2021

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.


@at-root { 


@use "sass:selector";

@mixin adv-nest($inner) {
  @at-root #{selector.unify(&, $inner)} {

.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.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to host Google fonts on your server and add them using CSS?CSSHow to list all PHP variables to debug the script?PHPHow to change CSS with jQuery?CSSHow states work in React?ReactHow to add today’s date in HTML input date value using JavaScript?JavaScriptThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQL