Going back to the root level with @at-root in SCSS

The @at-root takes the selector from its current nesting scope and moves that selector to the root of the file. This means that the following SCSS code:

.user {
    color: blue;
    @at-root .info {
        color: red;
    }
}

Will be compiled to:

.user { color: blue; }
.info { color: red; }
/* insead of :
.user { color: blue; }
.user .info { color: red; } */

It is useful as it allows us to group CSS rules but not to increase the specificity of these rules, making them easier to override if needed.

And this is true even in the case of multiple nesting. It will move the @at-root declaration at the top no matter how deep the nesting goes:

.container {
    .item {
        @at-root .title {
            color: red;
        }
    }
}
/* will be compiled just to .title { color: red; } */

One small this to note is using the @at-root with media queries. We can use @at-root (without: media) and @at-root (with: media) to decide if we want to still keep the media query or not.

@media (max-width: 600px) {
   .user {
      height: 8px;
      @at-root (without: media) {
            // rules here
      }
   }
}

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X