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.

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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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
3 JavaScript methods to use when you want to go back and forth in historyJavaScriptABS and NEG functions in Envision BasicEnvision BasicHow to Remove PHP File Extensions From Your Website URLs?PHPWordPress: How to display slider repeater fields in ACF?WordPressHow to concatenate variable with string in Swift?SwiftAngular 9 time clock update every minute, second, hourAngular