Escape Sass’ nesting

Johannes Krtek on

Nesting is definitely a nice thing™ when using Sass to write your stylesheets with attitude. Yes, it’s true that one tends to go a little overboard with it at first – producing larger files in the process than necessary – but let’s face it: the syntactical elegance of Sass stems mostly from its nested nature.

When it comes to global switches though, our euphoria about nesting may just blast off faster than, well … than you can say “blast off.”

To explain our euphoria’s sudden disappearance, let’s assume we have a very specific element which requires a web-font. And realistically enough, in order to avoid the infamous FOUT, our web-font supplier generously provides us with a global switch (typically courtesy of Google’s and TypeKit’s WebFont Loader). That is to say, the class .wf-loading is added to the html tag whilst the font is being fetched.

During the loading process we want to hide some affected elements rather than all elements. In all likelihood, this means we will have to tell some deeply nested element that it should care about that global switch all the way at the root of the nesting tree. And this, dear reader, is when our hero, the & referencing parent selector, comes to our rescue:

// Imagine lots of parent elements out here!
.parent {
  .deeply-nested-style {
    font-family: "brandon-grotesque";

    .wf-loading & {
      visibility: hidden;
    }
  }
}

is compiled to:

.parent .deeply-nested-style {
  font-family: "brandon-grotesque";
}

.wf-loading .parent .deeply-nested-style {
  visibility: hidden;
}

Yay! The & let’s us escape luckily without the tedious burden to repeat the nesting once again just for a global switch (think of Modernizr classes). Even though this useful Sass feature is well documented, it seems to have stayed a well-kept secret. Until now, that is.

Incidentally, this is also true for the @media rule which can be used in the same way to create in-place media queries without any need to build up the class hierarchy twice. Sass is truly awesome in every sense of the word (and thanks to the Hitchhiker’s Guide to the Galaxy we know all about those)!

Keep nesting!