You can also perform chaining by extending the selectors in the next selector, as shown in Listing
Chapter 3
■
advanCed SaSS
42
Listing 3-18. Output of Listing
3-17
.notification, .errorLooks, .error {
border-radius: 5px;
padding: 5px;
}
.errorLooks, .error {
Color: #F00;
Background-color: rgba(255, 0, 0, 0.5);
}
@extend Behind the Scenes
Inheritance isn’t as simple as it seems. Understanding how extending works will give you insight into how
selectors are inherited and thus will give you the ability to anticipate the output.
Let’s take example used in previous section. The principle behind @extend is that if .error extends
.notification, every instance of .error in the final stylesheet will be replaced with .notification, .error.
There are two things regarding @extend that you should keep in mind:
• Inheritance generates comparatively less CSS than mixins, which does a somewhat
similar thing. It only adds the selector in a comma-separated list and does not clone
the properties.
• Cascading applies to inheritance similarly to how it does in normal CSS. When two
rules with different values apply to the same element, cascading decides which rule
will be applied. Thus the last rule is always applied.
When to Use Selector Inheritance
Suppose you are developing a web page and writing style rules and you find that one of your classes
(.errorLooks) is a more specific version of another (.notification). How will you go about writing the
style rule?
• You could replicate the same style rules in both the classes. However, this would
result in lot of duplicate code and would go against the DRY principle.
• You could apply styles to group of selectors (.notification, .error). This is good,
but over time will increase the complexity of your style code.
• You could use @extend provided by Sass and allow .error inherit from
.notification. This makes the code far more readable and easier to understand.
Placeholder Selectors
While using Sass, you might come across situations where you want to write classes that you want to extend
into other classes but don’t want it to be rendered into the final compiled CSS file. For example, you want to
use a certain class containing code for rounded edges or margins that’s not useful independently.
This can be achieved in Sass with something known as placeholder selector, which is rendered by
prefixing the class name with %—for example %notification.