Is it possible to include the parent properties in an extended Sass class?

markedup picture markedup · Oct 21, 2014 · Viewed 9.4k times · Source

I'd like to implement something like the BEM model in my Sass library. But I'm struggling to find a clean way to do this.

For example, I'd like to declare a 'base' style for a common element, and then extend it with useful variations:

.container {
  margin: 10%;
  background: #eee;

  &-featured {
    border: 2px solid #999;
  }

}

The problem here is that the generated .container-featured class only contains the border property—Sass doesn't include the margin and background from its 'parent' class.

So you end up having to double up on classes in your markup to get the desired results:

<div class="container container-featured">
  ...
</div>

Is there some way to pull the properties from a parent class down into that modifier class, so you can get the same visual result just referencing the modifier class in your markup?

<div class="container-featured">
  <!-- has margin, background, and border styles via just modifier class -->
</div>

I've tried using mixins to do this, but things get verbose and repetitive very quickly:

@mixins container {
  margin: 10%;
  background: #eee;
}

.container {
  @include container;

  &-featured {
    @include container;
    border: 2px solid #999;
  }

}

Is there a simple, clean way of achieving this with Sass?

Answer

Colin Bacon picture Colin Bacon · Oct 21, 2014

What you are looking for is the @extend directive. @extend allows you share a set of CSS properties from one selector to another. This means that you would only need to use the container-featured class.

Example

.container {
  margin: 10%;
  background: #eee;

  &-featured {
    @extend .container;
    border: 2px solid #999;
  }
}

compiles to:

.container,
.container-featured {
    margin: 10%;
    background: #eee;
}

.container-featured {
    border: 2px solid #999;
}