tezvyn:

Sass @extend: Inherit Styles, Not HTML Classes

AI-drafted, machine-checkedSource: sass-lang.comintermediate

@extend lets one selector inherit styles from another, grouping them in the final CSS without adding classes to your HTML. Use it for modifier classes to keep markup clean. The footgun: overusing it can generate long, complex selectors, bloating your CSS.

WHY IT EXISTS Often, one component should be a variation of another, sharing most of its styles. The naive approach is to add multiple classes to the HTML, like class="alert alert-warning". This clutters markup, is error-prone, and mixes styling concerns into the HTML structure. @extend was created to solve this by establishing these relationships directly within the CSS.

THE MENTAL MODEL Think of @extend as telling Sass, "Wherever you see selector A, pretend you also see selector B." It doesn't copy style properties like a mixin does. Instead, it finds every style rule that targets selector A and adds selector B to its list, effectively grouping them in the final compiled CSS.

HOW IT WORKS When you write .error--serious { @extend .error; }, Sass doesn't just copy the styles from .error. Instead, it finds every instance of .error in your stylesheet (including .error:hover or div > .error) and adds the corresponding version of .error--serious to the selector list. The input .error { color: red; } and .error--serious { @extend .error; } becomes the output .error, .error--serious { color: red; }. This process, called "intelligent unification," happens after most other Sass compilation.

WHEN TO USE IT Use @extend when there is a clear "is-a" relationship between two classes. It's perfect for component modifiers in methodologies like BEM, where .button--danger is a specific type of .button. This keeps your HTML clean, requiring only class="button--danger".

WHEN NOT TO USE IT Avoid extending generic, widely-used selectors (like .clearfix or .hidden). This can cause @extend to generate massive, bloated selector lists that are hard to debug and hurt performance. If you only want to reuse a block of properties without creating a semantic link between selectors, use a @mixin instead. A mixin copies the properties, which is more predictable and avoids selector bloat.

ONE CANONICAL EXAMPLE You want a serious error message that inherits from a basic error style but has a thicker border.

SCSS INPUT: .error { border: 1px solid red; background-color: #fdd; }

.error--serious { @extend .error; border-width: 3px; }

COMPILED CSS OUTPUT: .error, .error--serious { border: 1px solid red; background-color: #fdd; }

.error--serious { border-width: 3px; }

Read the original → sass-lang.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.