UX Design and Development course

Selector inheritance w/@extend

There are often cases when designing a page when one class should have all the styles of another class, as well as its own specific styles. The most common way of handling this is to use both the more general class and the more specific class in the HTML.

The @extend directive avoids these problems by telling Sass that one selector should inherit the styles of another selector. For example:

h1 {
  font-size: 3.83333em;
  line-height: 1.17391em;
  margin-bottom: 0.3913em;
  font-weight: normal;
  font-fmaily: "Helvetica Neue", Arial, sans-serif;
  text-decoration: uppercase;
}

h2 {
  font-size: 2.66667;
  line-height: 1.125;
  margin-bottom: 0.5625;
  @extend h1;
}

.large-copy {
  @extend h1;
}

For more information and examples as to how the @extend directive works, be sure to read Sass Extends: be aware of the loop.

SassMeister Gist

Selector inheritance w/silent @extend

Sometimes you’ll write styles for a class that you only ever want to @extend, and never want to use directly in your HTML. This is especially true when writing a Sass library, where you may provide styles for users to @extend if they need and ignore if they don’t.

If you use normal classes for this, you end up creating a lot of extra CSS when the stylesheets are generated, and run the risk of colliding with other classes that are being used in the HTML. That’s why Sass supports “placeholder selectors” (for example, %foo).

Placeholder selectors look like class and id selectors, except the # or . is replaced by %. They can be used anywhere a class or id could, and on their own they prevent rulesets from being rendered to CSS.

%large-type {
  font-size: 3.83333em;
  line-height: 1.17391em;
  margin-bottom: 0.3913em;
  color: #333333;
}

h1 {
  @extend %large-type;
}

h2 {
  @extend %large-type;
  font-size: 2.66667em;
}

.big-letters {
  @extend %large-type;
}

For more information and examples as to how the @extend directive works, be sure to read Sass Extends: be aware of the loop.

SassMeister Gist