0
0
SASSmarkup~7 mins

Recursive mixins in SASS

Choose your learning style9 modes available
Introduction

Recursive mixins help you repeat a style or calculation many times without writing it over and over. They save time and keep your code clean.

When you want to create repeating patterns like nested boxes or shapes.
When you need to generate a series of styles that depend on a number, like spacing or colors.
When you want to build complex layouts that grow step by step.
When you want to avoid writing the same code multiple times for similar elements.
When you want to create animations or effects that repeat with small changes.
Syntax
SASS
@mixin mixin-name($count) {
  @if $count > 0 {
    // Your styles here
    @include mixin-name($count - 1);
  }
}

The mixin calls itself with a smaller number until it reaches zero.

Use @if to stop the recursion and avoid infinite loops.

Examples
This mixin demonstrates recursion by setting box-shadow with decreasing blur radius ($count * 2px) each time. However, only the final declaration (smallest blur when $count=1) applies, as later ones override earlier ones.
SASS
@mixin box-shadow-recursive($count) {
  @if $count > 0 {
    box-shadow: 0 0 #{ $count * 2 }px rgba(0, 0, 0, 0.1);
    @include box-shadow-recursive($count - 1);
  }
}
This mixin demonstrates recursion by setting decreasing padding values ($count rem). However, only the final (smallest) padding applies due to overriding.
SASS
@mixin padding-recursive($count) {
  @if $count > 0 {
    padding: #{ $count }rem;
    @include padding-recursive($count - 1);
  }
}
Shows what happens if no styles are added during recursion (nothing visible).
SASS
@mixin empty-recursive($count) {
  @if $count > 0 {
    // No styles here
    @include empty-recursive($count - 1);
  }
}
Sample Program

This code applies a recursive mixin to create multiple border and padding declarations with lightness scaled by $count (higher count = lighter). Due to CSS overriding, only the deepest recursion's styles apply: 1px solid border at ~10% lightness (dark gray) and 0.5rem padding.

SASS
@use "sass:color";

@mixin recursive-border($count) {
  @if $count > 0 {
    border: 1px solid color.scale(black, $lightness: $count * 10%);
    padding: 0.5rem;
    @include recursive-border($count - 1);
  }
}

.box {
  @include recursive-border(3);
  background-color: #eee;
  width: 10rem;
  height: 10rem;
}
OutputSuccess
Important Notes

Recursive mixins run until the stop condition is met, so always include a condition like @if $count > 0.

Too many recursive calls can slow down your CSS compilation.

Use recursion when you want to generate repeated styles that depend on a number, but for simple repeats, loops might be easier.

Summary

Recursive mixins call themselves to repeat styles multiple times.

Always include a stop condition to avoid infinite loops.

Useful for creating layered or repeated styles that change step by step.