dots Created with Sketch.
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.

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
How to create a Child Theme in WordPress?WordPressHow to change HTML content on click using JavaScript?JavaScriptHow to add and remove capabilities from a role in WordPress?WordPressIntroduction to components and templates Part 2: Templates and viewsAngularHow to change perception and behavior of a person for acceptance of new systems?MiscellaneousHow to add new elements with swing animation using JavaScript and CSS?CSS