0
0
SASSmarkup~5 mins

Extend limitations and gotchas in SASS

Choose your learning style9 modes available
Introduction
Extend helps reuse styles in Sass, but it has some limits and tricky parts to know so your styles work well.
You want to share common styles between buttons and links.
You want to avoid repeating the same CSS rules in many places.
You want to keep your CSS smaller by reusing selectors.
You want to organize styles better by grouping similar styles.
You want to avoid copying and pasting styles manually.
Syntax
SASS
@extend selector;
Use @extend inside a CSS rule to copy styles from another selector.
The selector you extend must exist somewhere in your Sass or CSS.
Examples
The .link class will get all styles from .button plus its own.
SASS
.button {
  background: blue;
  color: white;
}

.link {
  @extend .button;
  text-decoration: underline;
}
The .error class reuses .alert styles and adds a pink background.
SASS
.alert {
  border: 1px solid red;
  padding: 1rem;
}

.error {
  @extend .alert;
  background: pink;
}
Sample Program
This Sass code creates a base .card style. Then .highlight and .note reuse it with some changes. The background of .highlight is a darker white, and .note has a dashed border.
SASS
@use 'sass:color';

.card {
  border: 2px solid black;
  padding: 1rem;
  background: white;
}

.highlight {
  @extend .card;
  background: color.scale(white, $lightness: -20%);
}

.note {
  @extend .card;
  border-style: dashed;
}
OutputSuccess
Important Notes
Extending works by combining selectors in the final CSS, so if you extend many selectors, the CSS can get complex.
You cannot extend selectors that are inside media queries or nested in ways that Sass cannot find.
Extending placeholder selectors (like %placeholder) is safer because they don't output CSS on their own.
Summary
@extend helps reuse styles but merges selectors in the output CSS.
Be careful with complex selectors and nesting because @extend might not work as expected.
Use placeholder selectors to avoid unwanted CSS output when extending.