BudiBadu Logo
Samplebadu

SCSS by Example: Inheritance

Sass 3.x+

Sharing styles between selectors with this code example demonstrating @extend directive for selector inheritance, how extended selectors are grouped in compiled CSS, and style override patterns for inherited properties.

Code

// Base styles
.message {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  @extend .message;
  border-color: green;
}

.error {
  @extend .message;
  border-color: red;
}

.warning {
  @extend .message;
  border-color: yellow;
}

Explanation

The @extend directive allows one selector to inherit all styles from another selector. When SCSS encounters @extend, it modifies the selector list in the compiled CSS rather than duplicating properties. For example, .success { @extend .message; } results in .message, .success, .error, .warning { ... } in the final CSS, grouping all selectors that share the same base styles.

This selector grouping mechanism produces more efficient CSS output compared to mixins, as the shared properties appear only once in the stylesheet. However, @extend can generate complex selector chains when used with nested selectors or when extending selectors that themselves extend others. The compiled output includes all combinations of selectors, which can lead to unexpected specificity issues and bloated CSS if not used carefully.

Properties defined after the @extend directive override the inherited values, allowing for variations on a base theme. The inheritance chain is resolved at compile time, meaning all extensions must be resolvable to actual selectors in the source files. Attempting to extend a selector that doesn't exist results in a compilation error, ensuring type safety for style inheritance patterns.

Code Breakdown

2
.message defines base styles that will be inherited by other selectors.
9
@extend .message; inherits all properties from .message selector.
10
border-color: green; overrides inherited border-color property.
8-20
Compiles to grouped selector .message, .success, .error, .warning { ... }.