Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Sass Extend

DZone's Guide to

Sass Extend

While @extend is not always advisable to use, it does have its place. Read on to learn more about this Sass function and placeholders in Sass as well.

· Web Dev Zone ·
Free Resource

Learn how Crafter’s Git-based content management system is reinventing modern digital experiences.

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

Extend represents the next (after import) extra Sass feature and if you set Sass and do 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.

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

The next level includes one extra thing: a placeholder class. If you're missing variables in CSS, you will not miss them 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 the 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 out that @extend should be carefully handled. Always 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 a better practice than @extend (example).

Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.

Topics:
web dev ,css ,css preprocessor ,sass

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}