@extend
is a useful directive for sharing sets of related properties that get repeated in your stylesheets without repeating code like the mixin does.
Inherit the Properties of Selectors
All the base styles defined in the .btn
rule are now applied to .btn-callout
and .btn-info
but not re-written inside of them. Whereas the @include
directive you learned about earlier clones the code inside of @mixin
and duplicates it in the CSS output over and over again. Extend makes the output more compact by grouping the selectors that share the same properties.
SCSS
.btn {
color: $white;
display: inline-block;
font-weight: bold;
text-decoration: none;
text-transform: uppercase;
padding: 0.75em 1.5em;
border-radius: 0.35em;
}
.btn-callout {
@extend .btn;
font-size: 1.1em;
background-color: $color-secondary;
}
.btn-info {
@extend .btn;
font-size: 0.85em;
background-color: $color-primary;
margin-top: auto;
}
CSS
.btn, .btn-callout, .btn-info {
color: #fff;
display: inline-block;
font-weight: bold;
text-decoration: none;
text-transform: uppercase;
padding: 0.75em 1.5em;
border-radius: 0.35em; }
.btn-callout {
font-size: 1.1em;
background-color: #b13c69; }
.btn-info {
font-size: 0.85em;
background-color: #278da4;
margin-top: auto; }
Extend Placeholder Selectors via %
When you extend regular selectors, like classes and IDs, they get output to CSS. Sass has a special type of selector, called a placeholder selector, that won’t appear in the CSS output unless extended.
SCSS
%btn {
color: $white;
display: inline-block;
border-radius: 10px;
&:hover {
color: $white;
opacity: 0.8;
}
&:active {
opacity: initial;
}
}
.btn {
&-default {
@extend %btn;
font-size: 1.1em;
background-color: $color-secondary;
}
&-info {
@extend %btn;
font-size: 0.85em;
background-color: $color-secondary;
}
}
CSS
.btn-default, .btn-info {
color: #fff;
display: inline-block;
border-radius: 10px;
}
.btn-default:hover, .btn-info:hover {
color: $white;
opacity: 0.8;
}
.btn-default:active, .btn-info:active {
opacity: initial;
}
.btn-default {
font-size: 1.1em;
background-color: $color-secondary;
}
.btn-info {
font-size: 0.85em;
background-color: $color-secondary;
}