Default Argument Values

Give arguments sensible defaults so callers can omit them.

Syntax@mixin name($a, $b: default) { }

Mixin parameters can have default values, written with a colon. If the caller omits that argument, the default is used.

This makes mixins convenient for the common case while still flexible for special cases. Order matters: put required parameters first and defaulted ones after, or use named arguments to skip around them.

Example

Example · css
@mixin button($bg: #CC6699, $color: white, $radius: 4px) {
  background: $bg;
  color: $color;
  border-radius: $radius;
  padding: 8px 16px;
}

.btn         { @include button; }                 // all defaults
.btn-accent  { @include button(#6699CC); }        // custom bg
.btn-pill    { @include button($radius: 999px); } // named skip

When to use it

  • A shadow mixin defaults to a subtle elevation so most components just write @include shadow() and only buttons override with @include shadow(2).
  • A padding mixin defaults to the design system's standard spacing so authors only pass arguments when a non-standard size is needed.
  • A transition mixin defaults to 'all 0.2s ease' so typical usage requires no arguments, but animation-heavy components can customize duration and easing.

More examples

Mixin with default argument

The mixin defaults to elevation level 1, so most callers omit the argument while modals opt into a stronger shadow by passing 3.

Example · css
@mixin shadow($level: 1) {
  @if $level == 1 { box-shadow: 0 1px 3px rgba(0,0,0,.12); }
  @if $level == 2 { box-shadow: 0 4px 6px rgba(0,0,0,.15); }
  @if $level == 3 { box-shadow: 0 10px 15px rgba(0,0,0,.2); }
}

.card    { @include shadow; }      // level 1
.modal   { @include shadow(3); }   // level 3

Transition mixin with all defaults

Three default arguments cover the common case with no arguments; any combination can be overridden individually.

Example · css
@mixin transition(
  $property: all,
  $duration: 0.2s,
  $easing:   ease
) {
  transition: $property $duration $easing;
}

.link  { @include transition; }
.modal { @include transition(opacity, 0.3s, ease-in-out); }

Keyword argument override

Passes only the $padding keyword argument by name, leaving $bg and $color at their defaults — a clean API for partial overrides.

Example · css
@mixin button(
  $bg:      #2563eb,
  $color:   white,
  $padding: 0.5rem 1rem
) {
  background: $bg;
  color:      $color;
  padding:    $padding;
}

.btn-lg { @include button($padding: 0.75rem 2rem); }

Discussion

  • Be the first to comment on this lesson.