Skip to content

Help us create more tutorials! Make a donation using the Donate button or become a member using the button below to hide this banner and track your progress.

extend – Sass

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

Demo

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 Course