Sass and bem ftw

The parent selector in Sass is amazing. I love Sass for a lot of reasons, but this is a really big one (there are many other reasons I love Sass too, which is why I made a course on it).

In Sass, you can use nesting, which is when you nest a selector inside another selector. It’s powerful, though it can lead to some messy code if you aren’t careful. One really cool thing with nesting though, is if you combine it with the parent selector, it becomes really powerful.

To create a parent selector, you just have to use the ampersand character (&).

So a super basic example would be:

.parent {
  background: blue;

  &-child {
    background: red;
  }
}

That would output CSS which would look like this:

.parent {
  background: blue;
}

.parent-child {
  background: red;
}

A more realistic example

Abstract examples are the worst though, right? Here is a more realistic way that I might use it:

a {
  color: #555;
  &:hover {
    color: red;
    text-decoration: underline;
  }
  &:visited {
    color: purple;
  }
}

That will compile to CSS which look like this:

a {
  color: #555;
}
a:hover {
  color: red;
  text-decoration: underline;
}
a:visited {
  color: purple;
}

The other time it’s awesome is if you use something like the BEM naming convention for your class names, where you’ll have a component, such as a .button, and then you use modifiers to change the color, size, etc:

.button {
  display: inline-block;
  padding: .5em 1.25em;
  text-transform: uppcase;
  &--primary {
    background: $primary;
    color: white;
    &:hover {
      background: $primary-dark;
    }
  }
  &--accent {
    background: $accent;
    color: black;
    &:hover {
      background: $accent-dark;
    }
  }
}

This is just one of the many reasons that I love Sass! It’s an insanely powerful language that let’s your literally do some magic like automatically picking a text color to keep high contrast based on the background you set, among many other cool and awesome things. If you haven’t started playing with it yet, I hope this post inspires you to try it out!

Don't want to miss an article?

While creating my YouTube videos, I come across a lot of fun snippits of information and little known CSS properties that aren't really worth building full videos about. I share the cool little things I run across (like you read in this post), as well as some design tips and tricks, with a new post every Sunday. Sign up below to never miss a post.

No spam + you can unsub at any time :)