</>
Skip to content
Sass lessons (17/28)

Sass — Extend

Basic extend

.message {
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.success {
  @extend .message;
  background: #d4edda;
  color: #155724;
}

.error {
  @extend .message;
  background: #f8d7da;
  color: #721c24;
}

Placeholder selectors

%button-base {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.primary-btn {
  @extend %button-base;
  background: #3498db;
}

.secondary-btn {
  @extend %button-base;
  background: #2ecc71;
}

Placeholders are not output to CSS unless extended.

Extend vs Mixin

// Extend - shares selector, CSS output combined
%card {
  padding: 20px;
  background: white;
}

.card-a { @extend %card; }
.card-b { @extend %card; }

// Mixin - copies styles, separate output
@mixin card-styles {
  padding: 20px;
  background: white;
}

.box-a { @include card-styles; }
.box-b { @include card-styles; }

Grid system

%col {
  float: left;
  box-sizing: border-box;
  padding: 0 10px;
}

.col-1 { @extend %col; width: 8.33%; }
.col-2 { @extend %col; width: 16.66%; }
.col-3 { @extend %col; width: 25%; }
.col-4 { @extend %col; width: 33.33%; }
.col-6 { @extend %col; width: 50%; }

Button variants

%btn {
  display: inline-block;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
}

.btn { @extend %btn; }
.btn-primary { @extend %btn; background: #3498db; color: white; }
.btn-danger { @extend %btn; background: #e74c3c; color: white; }

Limitations

// Cannot extend classes with @media
@media screen {
  .base { color: red; }
}

// This fails
@media screen {
  .child {
    @extend .base; // ERROR
  }
}

// Use mixin instead
@mixin base-styles {
  color: red;
}

.child {
  @include base-styles;
}

Mini Practice

  1. Create a button base with extend variants
  2. Build a card system using placeholders
  3. Create an alert component with extend
  4. Compare CSS output between extend and mixin

Up Next

Continue with Control Flow — conditionals and loops.

Related Topics

Frequently Asked Questions about Extend

What is Extend in Sass?

Extend is a fundamental concept in Sass. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Extend?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Extend.

Why is Extend important in Sass?

Extend is essential for Sass development. Understanding this concept will help you write better code and solve real-world problems more effectively.