Article: Structuring CSS Class Selectors with Sass

Extract for SitePoint article “Structuring CSS Class Selectors with Sass” by Hugo Giraudel

Published July 9, 2015

CSS naming conventions are legions. You probably know BEM and SMACSS already (the latter also being more than naming conventions). There is also OOCSS which is more like a full methodology. They all heavily rely on CSS class selectors, as they are heavily re-usable.

Using Sass can help writing those selectors in a more modular fashion. through selector nesting and mixins, we can come up with fancy crazy solutions to build the desired API. In this article, I”ll (re-)introduce a few of these ways, listing what I feel are the pros and cons of each of them.

Native Selector Nesting

Having a way to nest selectors in order not to have to repeat the original block name has been a long asked feature in Sass. In version 3.3 of Sass, this feature has finally been introduced. First with a very odd syntax during the beta, later changed for a better one when the stable version went live. The reasons behind this change are explained by Natalie Weizenbaum in this article.

Basically, the reference selector (&) can be used as part of a sub-class name in order to create another class name from the first at root-level of the document (meaning @at-root is not needed here).

.foo {
  // Styles for `.foo`
  &-bar {
    // Styles for `.foo-bar`

This feature has soon be over-exploited to write BEM selectors, such as the very popular media object:

.media {
  // Styles for `.media` block
  &__img {
    // Styles for `.media__image` element
    &--full {
      // Styles for `.media__image--full` modified element
  &--new {
    // Styles for `.media--new` midifier

The previous code would be compiled to:

.media {}
.media__img {}
.media__img--full {}
.media--new {}

Continue reading article on SitePoint …

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.