How to Use Placeholder Selectors and Extends in Sass for Code Reuse

In modern CSS development, Sass offers powerful features to make your stylesheets more efficient and maintainable. Two of the most useful features are placeholder selectors and the @extend directive. These tools help you reuse code and keep your styles consistent across your project.

What Are Placeholder Selectors?

Placeholder selectors in Sass are special selectors that start with a ‘%’ symbol. They are not rendered in the CSS output unless extended. Placeholders are used to define common styles that can be shared across multiple selectors without duplicating code.

Using Placeholder Selectors

To create a placeholder, define it with the ‘%’ prefix:

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

You can then extend this placeholder in your actual selectors:

.primary-button {
  @extend %button-style;
  background-color: blue;
  color: white;
}

This approach promotes code reuse and keeps your stylesheets organized.

The @extend Directive

The @extend directive in Sass allows you to include all styles from a placeholder or another selector into your current rule. It reduces duplication and simplifies updates.

Extending Placeholders

As shown earlier, you can extend a placeholder like this:

.secondary-button {
  @extend %button-style;
  background-color: gray;
  color: black;
}

Extending Other Selectors

In addition to placeholders, you can extend existing selectors:

.alert {
  padding: 15px;
  background-color: red;
  color: white;
}

.error {
  @extend .alert;
  border: 2px solid darkred;
}

Using @extend helps maintain consistency and reduces the need to duplicate styles across multiple classes.

Best Practices for Using Placeholders and Extends

  • Use placeholders for styles shared across multiple selectors.
  • Avoid overusing @extend, as it can increase CSS specificity and size.
  • Combine @extend with mixins for more flexible styling.
  • Organize your placeholders logically for easier maintenance.

By effectively leveraging placeholder selectors and @extend, you can write cleaner, more maintainable Sass code that promotes reuse and consistency throughout your projects.