0
0
SASSmarkup~5 mins

@extend directive in SASS

Choose your learning style9 modes available
Introduction

The @extend directive helps you reuse styles from one CSS selector in another. It keeps your code shorter and easier to manage.

When you want multiple elements to share the same styles without repeating code.
When you have a base button style and want to create variations like primary or secondary buttons.
When you want to keep your CSS organized by grouping similar styles together.
When you want to avoid copying and pasting the same CSS rules in many places.
When you want to make future style changes easier by updating one place.
Syntax
SASS
@extend selector;

The selector is the CSS class or element whose styles you want to reuse.

You write @extend inside a CSS rule to inherit styles from another rule.

Examples
This makes .button-primary use all styles from .button plus its own background color.
SASS
.button-primary {
  @extend .button;
  background-color: blue;
}
.alert-error inherits styles from .alert and adds red text color.
SASS
.alert-error {
  @extend .alert;
  color: red;
}
The h1 element will have all styles from .title plus a bigger font size.
SASS
h1 {
  @extend .title;
  font-size: 2rem;
}
Sample Program

This example shows a base button style in .button. The .button-primary and .button-danger classes reuse the base styles using @extend and add their own colors.

In the browser, you will see three buttons with consistent padding and shape but different background colors.

SASS
@use 'sass:color';

.button {
  padding: 1rem 2rem;
  border-radius: 0.5rem;
  background-color: #eee;
  color: #333;
  border: none;
  cursor: pointer;
}

.button-primary {
  @extend .button;
  background-color: #007bff;
  color: white;
}

.button-danger {
  @extend .button;
  background-color: #dc3545;
  color: white;
}

/* HTML example to use these classes */

/*
<button class="button">Normal</button>
<button class="button-primary">Primary</button>
<button class="button-danger">Danger</button>
*/
OutputSuccess
Important Notes

Do not overuse @extend because it can create complex CSS selectors that are hard to debug.

@extend works best with classes, not with IDs or element selectors.

Use @extend to keep your styles DRY (Don't Repeat Yourself) and easier to maintain.

Summary

@extend lets one CSS rule reuse styles from another.

It helps keep your CSS code shorter and organized.

Use it to share common styles like buttons or alerts across different classes.