Mixins with parameters
A mixin becomes really useful when it takes parameters — values that change from call to call. Parameters are listed in parentheses like variables: .button-variant(@background; @color). One mixin then gives you a blue, a yellow and a red button.
Parameters
Describe the mixin in styles/mixins.less:
// styles/mixins.less
.button-variant(@background; @color) {
color: @color;
background: @background;
}And call it with different values in styles/components/buttons.less:
// styles/components/buttons.less
.btn-primary {
.button-variant(#2563eb; white);
}
.btn-warning {
.button-variant(#facc15; black);
}// styles/main.less
@import "mixins";
@import "components/buttons";.btn-primary {
color: white;
background: #2563eb;
}
.btn-warning {
color: black;
background: #facc15;
}<style>
.btn-primary {
color: white;
background: #2563eb;
}
.btn-warning {
color: black;
background: #facc15;
}
</style>
<button class="btn-primary">Save</button>
<button class="btn-warning">Delete</button>Semicolon or comma
Arguments can be separated with commas or with semicolons. The semicolon is recommended: then a comma inside a value does not split it into two arguments.
// styles/main.less
.font(@family; @size) {
font-family: @family;
font-size: @size;
}
.title {
.font(Georgia, serif; 24px);
}.title {
font-family: Georgia, serif;
font-size: 24px;
}Georgia, serif went into the first parameter as a whole, because the separator was a semicolon.
Default values
A parameter can have a default value — then it may be skipped:
// styles/mixins.less
.button-variant(@background; @color: white) {
color: @color;
background: @background;
}Now .button-variant(#2563eb); gives white text, and .button-variant(#facc15; black); still gives black.
Named arguments
Arguments can be passed by name — then the order does not matter, and the call reads without looking into the mixin:
// styles/main.less
.button-variant(@background; @color: white) {
color: @color;
background: @background;
}
.btn-dark {
.button-variant(@color: #f9fafb; @background: #111827);
}.btn-dark {
color: #f9fafb;
background: #111827;
}All arguments at once
Inside a mixin the @arguments variable holds all passed values separated by spaces. This is handy for shorthand properties:
// styles/main.less
.shadow(@x; @y; @blur; @color) {
box-shadow: @arguments;
}
.card {
.shadow(0; 2px; 8px; #d1d5db);
}.card {
box-shadow: 0 2px 8px #d1d5db;
}Common mistake
A mixin with a required parameter cannot be called without an argument. The call .button-variant(); stops compilation with the error No matching definition was found for .button-variant(). Pass a value or give the parameter a default.