The @extend Rule

Share styles between selectors by grouping them.

Syntax.a { color: red; } .b { @extend .a; }

@extend makes one selector inherit the styles of another. Instead of copying declarations, Sass adds the extending selector to the selector list of the extended rule, so they share one block of CSS.

This produces smaller output than a mixin when many selectors share the exact same styles, because the declarations appear only once.

Example

Example · css
.message {
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.message--success {
  @extend .message;
  border-color: #5cb85c;
}

/* Compiles to:
.message, .message--success {
  padding: 12px; border: 1px solid #ccc; border-radius: 4px;
}
.message--success { border-color: #5cb85c; }
*/

When to use it

  • A developer uses @extend to share identical .error-message styling between form validation errors and toast notifications without duplicating declarations.
  • A team extends a common %card-shadow rule across product cards, user cards, and modal overlays so the shadow definition lives in one place.
  • A developer refactors a stylesheet to @extend a .visually-hidden base class from multiple screen-reader utility classes instead of copying 6 identical lines.

More examples

Basic @extend between selectors

Both .success and .error extend .message, compiling to a grouped selector that shares the padding, radius, and font-size rules.

Example · css
.message {
  padding: 0.75rem 1rem;
  border-radius: 4px;
  font-size: 0.875rem;
}

.success {
  @extend .message;
  background: #d1fae5;
  color: #065f46;
}

.error {
  @extend .message;
  background: #fee2e2;
  color: #991b1b;
}

Extend adds to selector group

Shows that @extend groups the extenders into the base selector's rule, emitting shared properties once and unique properties separately.

Example · css
// Sass
.btn { display: inline-flex; padding: 0.5rem 1rem; }
.btn-primary { @extend .btn; background: #2563eb; }
.btn-danger  { @extend .btn; background: #dc2626; }

// Output (simplified)
// .btn, .btn-primary, .btn-danger { display: inline-flex; padding: ... }
// .btn-primary { background: #2563eb; }
// .btn-danger  { background: #dc2626; }

Extending state selectors

Extending .input automatically pulls in the .input:focus rule too, so .textarea inherits both the base and focus styles.

Example · css
.input {
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 0.5rem;
}

.input:focus {
  border-color: #2563eb;
  outline: 2px solid rgba(37,99,235,.25);
}

.textarea {
  @extend .input;
  resize: vertical;
}

Discussion

  • Be the first to comment on this lesson.