# Mixins
Writing the same code repeatedly is a common pattern in CSS. Sass provides a feature called mixin which allows you to reuse code across your stylesheets. Typically, a mixin is written after the variable declarations and used throughout the Sass file.
# Basic mixins
A mixin is defined using the @mixin
directive followed by a name, and can accept parameters within round brackets. For instance, let's define a mixin called color-combo
that takes two parameters: $front
and $back
.
@mixin color-combo($front, $back) { color: $front; background-color: $back; }
Copied!
2
3
4
To use a mixin, we use the @include
directive followed by the mixin name and the required arguments.
$color: #cf649a; // Mixin declaration @mixin color-combo($front, $back) { color: $front; background-color: $back; } h1 { @include color-combo($color, inherit); }
Copied!
2
3
4
5
6
7
8
9
10
11
Comments in Sass
In Sass, single-line comments //...
are not included in the compiled CSS, in contrast to multi-line comments /*...*/
.
Sass naming conventions
Sass' naming conventions are inherited from CSS. Lowercase, hyphen-separated names, like color-combo
in the example above, are considered standard.
# Mixins with parameters
Mixins can have optional parameters, allowing us to define a default style that can be easily overridden. This can be achieved by assigning default values to the parameters in the mixin definition.
# Example without arguments
In this case, if we include the mixin without arguments, it will use the default values.
@mixin color-combo($front: #151515, $back: #f1f1f1) { color: $front; background-color: $back; }
Copied!
2
3
4
# Example with one argument
If we include the mixin with one argument, it will be assigned to the first parameter and the second parameter will use its default value.
@mixin color-combo($front: #151515, $back: #f1f1f1) { color: $front; background-color: $back; }
Copied!
2
3
4
# Example with named parameters
We can also include parameters by their names to avoid confusion.
@mixin color-combo($front: #151515, $back: #f1f1f1) { color: $front; background-color: $back; }
Copied!
2
3
4
READING TIP
For more details, you can check the official Sass documentation on @mixin and @include (opens new window)
# Interactive example
Below is an interactive example showcasing the concepts discussed above.