Sass and bem ftw

Mar 1 2018

Hi, last week I mentioned a few Sass features that won me over and had me start using it. One of the others, which keeps me coming back to Sass, is the ampersand, which is sort of like a parent selector. In Sass, you can use nesting, and if you combine it with the ampersand character, it becomes really powerful. For example:

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;
    }
  }
}