Sass Mixins: Reusable Style Functions
Think of a Sass mixin as a function for CSS. It bundles style declarations you can reuse, avoiding repetitive code. Use it for common patterns like button styles or clearing floats. The footgun: mixins copy code everywhere, which can bloat your final CSS.
WHY IT EXISTS CSS lacks a native way to reuse groups of properties without creating utility classes like .text-center. This leads to either repetitive code in your stylesheets or non-semantic classes in your HTML. Mixins solve this by letting you define and reuse style blocks within the Sass preprocessor itself.
THE MENTAL MODEL A mixin is like a function for your styles. You define a block of CSS once using @mixin, give it a name, and then call it anywhere you need those styles using @include. Just like a function, it can accept arguments to dynamically change its output, making it incredibly flexible for creating variations of a style.
HOW IT WORKS You declare a mixin with @mixin my-mixin { ... }. The block can contain any CSS properties and even other Sass rules. To use it, you write @include my-mixin; inside a selector. The Sass compiler then copies the styles from the mixin directly into that selector in the final CSS output. You can also pass arguments, like @mixin button-style(bg-color) { background-color: bg-color; }, and then call it with @include button-style(blue);.
WHEN TO USE IT Use mixins for style patterns that are repeated across unrelated CSS selectors, especially when you need to pass parameters to create variations. Examples include: creating themed button variants, managing vendor prefixes for experimental CSS properties, or defining complex layout patterns like a flexbox container setup.
WHEN NOT TO USE IT Avoid using mixins for styles that should be grouped under a single, shared class rule. If multiple elements share the exact same block of styles without variation, using Sass's @extend with a placeholder selector is more efficient. @extend creates a comma-separated list of selectors for one rule block, whereas @include duplicates the entire rule block for each selector, which can bloat the CSS output.
ONE CANONICAL EXAMPLE A common use case is creating a mixin to reset the default styling of a list, which can then be included by other rules. @mixin reset-list { margin: 0; padding: 0; list-style: none; }
nav ul { @include reset-list; }
This compiles to CSS where the reset styles are copied directly into the nav ul rule, keeping your Sass organized and your HTML clean: nav ul { margin: 0; padding: 0; list-style: none; }
Read the original → sass-lang.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.