Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

extend – Sass

Demo

Summary

Sass extend example:

%custom-colors {
  background-color: green;
  color: yellow;
}

h1 {
  @extend %custom-colors;
}

p {
  @extend %custom-colors;
}

Compiled CSS:

p, h1 {
  background-color: green;
  color: yellow;
}

To see a live example of this code, view the Demo section below.

Details

The @extend rule in Sass allows you to group several CSS declarations together and reuse them in multiple rules.

The @extend feature uses the following format:

%extend-selector-name {
  property 1: value 1;
  property 2: value 2;
  // property 3...
}

.rule-1 {
  @extend %extend-selector-name;
}

.rule-2 {
  @extend %extend-selector-name;
}

The type of selector at the top of the code snippet is called a placeholder selector and starts with a %. This selector won’t appear on its own in the CSS output, but its declarations will appear wherever it’s extended.

It is also possible to extend an existing CSS rule:

.my-class {
  background-color: green;
  color: yellow;
}

.my-class-alternate {
  @extend .my-class;
  border: 1px black;
}

Exercises

First, recreate the Sass code in the embedded CodePen demo.

Then try changing the values in the extend section.

References

Sass Basics | Sass

@extend | Sass Documentation

Back to: Sass Reference