Sass Extend

Sass Extend

Please make sure to read my post on Sass Import because I didn't want to copy-paste the first part (it serves as an introduction to this post, as well).

Extend represents the next (after import) Sass extra feature and if you set Sass and not use @extend you just don’t know what you’re doing (or do you really?).

@extend

The @extend feature allows one selector to inherit the styles of another selector. Your job is just to free your mind and think outside of the CSS. Now when you're reset to Sass, you can reuse everything previously written, in other words, you can extend classes.

Sass

 .class1{
     width:100px;
     height:30px;
     color:red;
     background-color:#ababab;
 }
 
 .class2{
     @extend class1;
     border-radius:2px
 }

CSS:

 .class1, .class2{
     width:100px;
     height:30px;
     color:red;
     background-color:#ababab;
 }
 
 .class2{
     border-radius:2px;
 }

Placeholder

Next level includes one extra thing: a placeholder class. If you're missing variables in CSS, you will not miss it in Sass. A placeholder class is a special type of class that only prints when it is extended, and its functionality can be explained simply as a variable feature.

It is always used with @extend and it's syntax contains % instead of . in class. It is ignored in CSS output until it is used.

Sass

 %class-style{
     width:100px;
     height:30px;
     color:red;
     background-color:#ababab;
 }
 
 .class1{
    @extend %class-style;
 }
 
 .class2{
     @extend %class-style;
     border-radius:2px;
 }

CSS:

 .class1, .class2{
     width:100px;
     height:30px;
     color:red;
     background-color:#ababab;
 }
 
 .class2{
     border-radius:2px;
 }

Cons

It is frequently pointed that @extend should be carefully handled. Always first consider CSS selectors and their combination before @extend. Before using @extend also consider skipping nesting, because it often becomes messy(example). One more thing, using @mixin is usually considered to be the best practice than @extend (example).

Conclusion

@extend is defined with Sass and I described it. It has its pros and probably much more cons which just means that we should be careful with it (and research it thoroughly which I believe I did).

For more thorough research subscribe to our newsletter.