0
0
SASSmarkup~5 mins

Variable arguments in mixins in SASS

Choose your learning style9 modes available
Introduction

Variable arguments let you send any number of values to a mixin. This makes your styles flexible and reusable.

When you want a mixin to accept different numbers of colors for backgrounds.
When you need to add multiple padding or margin sizes without writing many mixins.
When you want to create a button style that can have any number of shadow layers.
When you want to pass a list of fonts to a font-family property easily.
Syntax
SASS
@mixin name($args...) {
  // styles using $args
}

The $args... means the mixin can take many arguments.

Inside the mixin, $args acts like a list of all passed values.

Examples
This mixin accepts any number of padding sizes and applies them.
SASS
@mixin padding($sizes...) {
  padding: $sizes;
}
This mixin uses the first and second colors from the list.
SASS
@mixin colors($colors...) {
  background: nth($colors, 1);
  border-color: nth($colors, 2);
}
This mixin combines multiple shadows into one property.
SASS
@mixin box-shadow($shadows...) {
  box-shadow: join($shadows, ', ');
}
Sample Program

This example shows a mixin that takes many padding sizes and applies them to a box. The box will have different padding on each side.

SASS
@mixin multi-padding($sizes...) {
  padding: $sizes;
}

.box {
  @include multi-padding(1rem, 2rem, 3rem, 4rem);
  background-color: lightblue;
  border: 2px solid navy;
}
OutputSuccess
Important Notes

You can use length($args) to find how many arguments were passed.

Use nth($args, n) to get the nth argument from the list.

Variable arguments help keep your code DRY (Don't Repeat Yourself).

Summary

Variable arguments let mixins accept any number of inputs.

Inside the mixin, arguments are treated as a list you can use with list functions.

This makes your styles more flexible and easier to maintain.