sass Nesting with @at-root


Example

Nesting is probably most often used to create more specific selectors, but it can also be used simply for code organization. Using the @at-root directive, you can ‘jump out’ of where you nest it in your Sass, bringing you back at the top level. Doing this allows you to keep styles grouped without creating more specificity than you need.

For example, you could to something like this :

.item {
    color: #333;

    @at-root {
        .item-wrapper {
            color: #666;

            img {
                width: 100%;
            }
        }
    }
    
    .item-child {
        background-color: #555;
    }
}

That would compile to this :

.item {
  color: #333;
}
.item-wrapper {
  color: #666;
}
.item-wrapper img {
  width: 100%;
}
.item .item-child {
  background-color: #555;
}

By doing this, all of our styles related to the .item class are together in the SCSS, but we don't necessarily need that class in every selector.

Excluding contexts

By default declarations inside @at-root will appear in any context. This means that rules inside a @media block for instance will remain there.

@media print {
  .item-wrapper {
    @at-root {
      .item {
        background: white;
      }
    }
  }
}

// Will compile to
@media print {
  .item {
    background: white;
  }
}

This is not always desired behavior, so you can exclude the media context, by passing media to the the without option of the @at-root directive.

@at-root (without: media) {..

For more information, see the official documentation