Codeskill

Learn to code, step by step

Mastering Mixins in SASS: The Power of Reusable Code

Mixins in SASS. Reusable blocks of CSS you can include wherever you need them. If you have ever copied the same vendor-prefixed properties into half a dozen selectors, mixins will save you time.

What are mixins in SASS?

Mixins work a bit like functions in a programming language. You define a block of CSS once and pull it into multiple places with @include. Less repetition, easier maintenance.

Cross-browser CSS used to mean writing the same property with different vendor prefixes on every selector. A mixin handles that in one place.

Basic structure of a mixin

A mixin is defined with the @mixin directive, followed by a name and optional parameters:

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
          border-radius: $radius;
}

This border-radius mixin takes a $radius parameter and applies it to the vendor-prefixed versions of the property.

Using mixins in your styles

Include a mixin with @include:

.button {
  @include border-radius(10px);
}

That compiles to:

.button {
  -webkit-border-radius: 10px;
     -moz-border-radius: 10px;
      -ms-border-radius: 10px;
          border-radius: 10px;
}

Mixins beyond the basics

Mixins are not just for vendor prefixes. You can use them for animations, grid layouts, responsive patterns, and anything you find yourself repeating.

A simple fade-in animation mixin:

@mixin fade-in($duration) {
  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
  animation: fadeIn $duration ease-in;
}

Then include it on any element that needs the effect:

.modal {
  @include fade-in(0.3s);
}

Best practices for using mixins

  1. Do not overuse: Mixins are useful, but too many make the stylesheet harder to follow. Use them when they genuinely reduce repetition.
  2. Name clearly: Pick names that describe what the mixin does.
  3. Keep it simple: Small, focused mixins are easier to reuse and maintain than large catch-all blocks.

Mixins are one of the features that make SASS worth the setup. Define once, include anywhere.

PreviousNesting in SASS: Bringing Order to CSS Chaos