Chepter 7: Sass @mixin

1. What Are @mixin and @include? (Super Simple First)

  • @mixin = Define a reusable block of styles (the “recipe”).
  • @include = Paste/use that block wherever you want (the “cook & serve”).

Mixins let you:

  • Avoid repeating the same CSS 20 times
  • Create parameterized styles (like functions)
  • Add logic, loops, conditionals inside reusable chunks
  • Inject custom styles from the caller (via @content)

This is not possible (or very clumsy) with native CSS custom properties or nesting alone in 2026.

2. Basic Syntax – No Arguments First

Define (usually in _mixins.scss or _utils.scss)

SCSS

Use (in any file after @use ‘mixins’;)

SCSS

→ Compiles to normal CSS without duplication.

3. Mixins with Arguments (The Real Power)

Arguments make mixins like mini-functions.

SCSS

Using them (keyword args = very readable!)

SCSS

Keyword arguments tip (2026 best practice): Always use keywords when >2–3 args or when skipping optionals — makes code self-documenting.

4. Argument Lists (…) – Flexible & Advanced

Capture any number of extra args.

SCSS

Or combine with fixed args:

SCSS

5. The Famous @content Block – Pass Custom Styles In

This is where mixins become magical — let the caller inject their own rules.

SCSS

Modern twist (Dart Sass ≥ 1.15.0 – fully supported 2026): Pass arguments to the @content block!

SCSS

6. Real-World Example – Button Family Mixin (Very Common Pattern)

SCSS

Usage:

SCSS

7. 2026 Best Practices & Gotchas

  • Put mixins in partials: _mixins.scss, _helpers.scss
  • Use @use ‘mixins’; (never old @import)
  • Prefer keyword arguments for clarity
  • Keep mixins focused — one concern per mixin (single responsibility)
  • Use @content sparingly — only when caller needs to inject styles
  • Avoid deep nesting inside mixins unless necessary
  • For deprecation: wrap old mixins and @warn (official pattern)
  • Watch out for mixed declarations breaking change (Dart Sass 1.77+): Don’t mix declarations after @include in the same block without wrapping in & { … } — or you’ll get warnings.

Example fix:

SCSS

→ Better:

SCSS

You’ve now got @mixin + @include mastered — this is where Sass really starts feeling like programming!

Next — want to combine mixins with maps for theme systems? Or build a full responsive typography mixin family? Or see how to handle vendor prefixes / fallback in modern Sass?

Just tell me — class is rolling! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *