@include keyword is used to include the code written in a mixin block. @mixin is used to group css code that has to be reused a no of times. Whereas the @extend is used in SASS to inherit(share) the properties from another css selector. @extend is most useful when the elements are almost same or identical.
The main difference between the two is in their compiled CSS file.
- @include example
SCSS file:@mixin text {
color : black ;
font-size : 30px ;
font-weight : bold ;
}
.hello{
@include text;
}
.world{
@include text;
}
|
Mixin duplicates the styles over all classes in the CSS.
Compiles CSS file:
.hello{
color: black;
font-size: 30px;
font-weight: bold;
}
.world{
color: black;
font-size: 30px;
font-weight: bold;
}
Mixin can also accept parameters if required, whereas this is not possible with extend.
for more details of @mixin visit here
- @extend example:
Here in this example, the two buttons will share the general properties for a button but they differ in background color only so using extend in cases like these where the elements are almost the same and only differ some properties using @extend is a good idea.
SCSS file:%button- format {
padding : 10px 20px ;
border-radius: 15px ;
color : black ;
}
.toolbar-button {
@extend %button- format ;
background-color : lightpink;
&:hover {
background-color : rgb ( 155 , 106 , 114 );
}
}
.status-bar-button {
@extend %button- format ;
background-color : lightblue;
&:hover {
background-color : blue ;
}
}
|
compiled CSS file:
.status-bar-button, .toolbar-button {
padding: 10px 20px;
border-radius: 15px;
color: black;
}
.toolbar-button {
background-color: lightpink;
}
.toolbar-button:hover {
background-color: #9b6a72;
}
.status-bar-button {
background-color: lightblue;
}
.status-bar-button:hover {
background-color: blue;
}
Conclusion:
SASS is a fantastic style sheet language and its both features @include and @extend both have pros and cons despite this, if used in the exact situation these can prove to be the best tools of SASS.