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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to change style of nth-child using jQuery?jQuery12 URLSearchParams methods in JavaScriptJavaScriptHow to change perception and behavior of a person for acceptance of new systems?MiscellaneousForcing the domain to serve securely using HTTPSMiscellaneousUNION and UNION ALL in PostgresPostgresHow to remove WordPress TinyMCE Editor buttons?WordPress