The @extend directive helps you reuse styles from one CSS selector in another. It keeps your code shorter and easier to manage.
@extend directive in 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.
.button-primary use all styles from .button plus its own background color..button-primary { @extend .button; background-color: blue; }
.alert-error inherits styles from .alert and adds red text color..alert-error { @extend .alert; color: red; }
h1 element will have all styles from .title plus a bigger font size.h1 {
@extend .title;
font-size: 2rem;
}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.
@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> */
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.
@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.