SyntaxStudy
Sign Up
SASS / SCSS The @extend Directive and Selector Inheritance
SASS / SCSS Beginner 1 min read

The @extend Directive and Selector Inheritance

The `@extend` directive allows one selector to inherit all the styles of another. When you write `@extend .message` inside a `.success` rule, SASS adds `.success` to every CSS rule that targets `.message`. The result is a comma-separated selector group in the output, sharing styles without code duplication and without adding extra classes to your HTML. This is fundamentally different from a mixin. A mixin copies the declarations to each call site, while `@extend` merges selectors. For large blocks of identical styles shared across many selectors, `@extend` produces more compact CSS because the declarations appear only once in the output. However, `@extend` has a significant limitation: it can only be used between selectors that appear in the same stylesheet context, and it can produce unexpectedly large selector chains when used inside media queries or across deeply nested rules. These issues led the SASS team to recommend using `%placeholder` selectors (silent classes) with `@extend` rather than extending real CSS classes.
Example
// ── Basic @extend ─────────────────────────────────────────────────────────────

.message {
    padding      : 1rem 1.25rem;
    border-radius: 4px;
    border       : 1px solid transparent;
    font-size    : 0.9375rem;
    line-height  : 1.5;
}

.message-success {
    @extend .message;
    background  : #d4edda;
    border-color: #c3e6cb;
    color       : #155724;
}

.message-error {
    @extend .message;
    background  : #f8d7da;
    border-color: #f5c6cb;
    color       : #721c24;
}

.message-warning {
    @extend .message;
    background  : #fff3cd;
    border-color: #ffeeba;
    color       : #856404;
}

// Compiled output — selectors are grouped, declarations appear once:
// .message, .message-success, .message-error, .message-warning {
//     padding: 1rem 1.25rem; border-radius: 4px; ...
// }
// .message-success { background: #d4edda; ... }
// .message-error   { background: #f8d7da; ... }
// .message-warning { background: #fff3cd; ... }

// ── Extending chained selectors ───────────────────────────────────────────────
.btn-base {
    display    : inline-block;
    cursor     : pointer;
    font-weight: 600;
}

.btn-primary {
    @extend .btn-base;
    background: #3498db;
    color     : #fff;
}