Sass @extend Directive
How to use the Sass @extend
directive to inherit styles from another property.
One of the features of Sass is the @extend
directive. The @extend
directive can be used to inherit styles from another property.
This can be useful when used on elements that share a base set of property values, but each one has its own extra property value/s.
Example
Take an alert box for example. You could have single style for all alerts. But each alert type might have its own color.
Here's an example:
This results in the following CSS being compiled:
Multiple Extends
You can use multiple @extend
directives within a selector.
So you can do this, for example:
The compiled CSS will look like this:
Chaining Extends
Another way of doing the above example is to chain the @extend
directives across the selectors.
So, instead of having two extends in the last selector, we could move the first extend up to the previous selector.
Like this:
Compiled CSS:
Placeholder Selectors
You might find yourself creating classes that you only ever use to extend another selector. In other words, you never actually use that class within your HTML code. Its sole purpose is to extend other selectors.
In cases like these, you probably don't want these selectors to be added to the compiled CSS. After all, they'll just increase the size of your CSS file and they'll never be used.
This is where placeholder selectors come in.
Placeholder selectors are similar to class selectors, however, instead of starting with a period (.
), they start with a percent sign (%
).
When you use a placeholder selector in your Sass file, it can be used to extend other selectors, but it won't be compiled into the final CSS.
So we can take the first example on this page, and change the .alert
selector to %alert
and see what happens.
Note that we need to change all references from .alert
to %alert
.
This results in the following CSS being compiled. Note that the %alert
selector is not included in the compiled CSS, even though the remaining selectors make use of it.