@extend in Sass

@extend is a feature of Sass that allows classes to share a set of properties with one another. Selectors that @extend a class in Sass will have their selector included right up next to the class it is extending, resulting in a comma separated list.

@extend .class-name;

.foo {
  color: black;
  border: 1px solid black;

.bar {
  @extend .foo;
  background-color: red;

Compiled to:

.foo, .bar {
  color: black;
  border: 1px solid black;

.bar {
  background-color: red;

.bar inherits from .foo, containing all properties of parent class .foo .

When you should use @extend

  1. Duplication of properties between classes is hard to avoid when putting together CSS.
  2. Extending complex selectors:a:hover.

The Cons

  1. extend can increase your CSS file size drastically and impact the performance of your CSS.We can only use @extend when the inherited class directly relates to the object we are inheriting from. It should be a variation of the object or style, rather than many unrelated elements.

Extending a deeper selector

.class1 + .class1 {
    //Some Styles
.classAnother {
    @extend .class1;

it will output:

.class1 + .class1,
.classAnother + .classAnother,
.class1 + .classAnother,
.classAnother + .class1{
    //Some Styles

Multiple extends

.class1 {//Style for class1}
.class2 {//Style for class2}
.class3 {
    @extend .class1,.class2

It will output:

.class1,.class3 {
    //Sytle for class1
.class2,class3 {
    //Style for class2

There's a more clear way to write the @extends is

.class3 {

It's more readable.

chaining extending

Although it's vaild,it's has some cons.

.class1 {//Styles for class1} .class2 {//Styles for class2;@extend .class1;} .class3 { @extend .class2; } It will output:

.class1,.class2,.class3{//Style for class1}
.class2,.class3{//Style for class2}

Massive extending

.class1 {//Styles for class1}
.class2, .class1 {//Styles for class2 and 1}
.class3{@extend .class1}

It'll output:

.class1, .class3 {//Style for class1}
.class1, .class2, .class1, .class3{//Style for class1 and 2 }

the class3 not only inherited from the class1,but also inherited from the instances where class1 is used in a descendant selector,

Preserving the source order

@extend works by inserting the extending selector […] anywhere in the stylesheet that the extended selector […] appears.

Media query problems

One of the biggest issues with @extend is its lack of support for extending from within a @media directive. Unfortunately, Sass doesn’t allow cross-media extensions.

Best Practices for @extend

  1. Make sure the extended selector is present only once in the stylesheet.
  2. Avoid extending from nested selectors.
  3. Don’t try extending from within a media query
  4. Avoid chaining @extend directives.