0
0
SASSmarkup~5 mins

Avoiding selector bloat from @extend in SASS

Choose your learning style9 modes available
Introduction

Using @extend in Sass helps reuse styles but can create very long CSS selectors. Avoiding this bloat keeps your CSS smaller and faster to load.

When you want to share styles between multiple selectors without repeating code.
When you notice your CSS file size growing too large after using <code>@extend</code>.
When you want to keep your CSS selectors simple and easy to read.
When you want to improve website loading speed by reducing CSS size.
When you want to avoid unexpected style conflicts caused by long combined selectors.
Syntax
SASS
@extend <selector>;

@extend copies styles from one selector to another.

It combines selectors in the output CSS, which can make selectors very long.

Examples
This shares .button styles with .primary using @extend.
SASS
.button {
  padding: 1rem;
  background: blue;
}

.primary {
  @extend .button;
  color: white;
}
.error gets all styles from .alert plus its own.
SASS
.alert {
  border: 1px solid red;
}

.error {
  @extend .alert;
  background: pink;
}
Sample Program

This example shows how @extend on normal classes creates combined selectors, which can get long. Using a placeholder selector (starting with %) avoids adding extra selectors to the output CSS, reducing bloat.

SASS
@use 'sass:color';

.button {
  padding: 1rem;
  background-color: blue;
  color: white;
}

.primary {
  @extend .button;
  font-weight: bold;
}

.secondary {
  @extend .button;
  background-color: color.scale(blue, $lightness: 30%);
}

/* Avoid selector bloat by using placeholders */
%button-base {
  padding: 1rem;
  background-color: blue;
  color: white;
}

.primary-alt {
  @extend %button-base;
  font-weight: bold;
}

.secondary-alt {
  @extend %button-base;
  background-color: color.scale(blue, $lightness: 30%);
}
OutputSuccess
Important Notes

Using placeholder selectors (like %button-base) helps avoid adding extra selectors to your CSS output.

Be careful: @extend merges selectors, so extending many selectors can create very long combined selectors.

Consider using mixins if you want to avoid selector bloat but still reuse styles.

Summary

@extend shares styles but can create long combined selectors.

Use placeholder selectors to avoid adding extra selectors and reduce CSS size.

Mixins are an alternative to @extend when you want to avoid selector bloat.