Pattern matching
In Less you can declare several mixins with the same name. On a call Less compares the arguments with the declarations and applies every one that fits. This is called pattern matching. One call then picks the right variant of the styles without any conditions.
Choosing by value
Instead of a parameter name a declaration can contain a specific value. Then the mixin fits only a call with that value. Describe the message variants in styles/mixins.less:
// styles/mixins.less
.alert(success) {
color: #166534;
background: #dcfce7;
}
.alert(danger) {
color: #991b1b;
background: #fee2e2;
}
.alert(@_) {
padding: 12px 16px;
border-radius: 8px;
}@_ is a parameter whose name does not matter: it fits any value. That is why the shared styles always apply. Call the mixin:
// styles/components/alerts.less
.alert-success {
.alert(success);
}
.alert-danger {
.alert(danger);
}// styles/main.less
@import "mixins";
@import "components/alerts";.alert-success {
color: #166534;
background: #dcfce7;
padding: 12px 16px;
border-radius: 8px;
}
.alert-danger {
color: #991b1b;
background: #fee2e2;
padding: 12px 16px;
border-radius: 8px;
}<style>
.alert-success {
color: #166534;
background: #dcfce7;
padding: 12px 16px;
border-radius: 8px;
}
.alert-danger {
color: #991b1b;
background: #fee2e2;
padding: 12px 16px;
border-radius: 8px;
}
</style>
<div class="alert-success">The post is published.</div>
<div class="alert-danger" style="margin-top: 8px">Could not save the post.</div>Each class received its own colours plus the shared padding from .alert(@_).
Choosing by the number of arguments
Mixins with the same name also differ by the number of parameters. Less picks the one that fits the number of passed values:
// styles/main.less
.size(@side) {
width: @side;
height: @side;
}
.size(@width; @height) {
width: @width;
height: @height;
}
.avatar {
.size(48px);
}
.banner {
.size(100%; 240px);
}.avatar {
width: 48px;
height: 48px;
}
.banner {
width: 100%;
height: 240px;
}A variable number of arguments
Three dots after a parameter name collect all remaining arguments into one variable. This is how you write mixins for properties that take a list, such as several shadows:
// styles/main.less
.shadows(@list...) {
box-shadow: @list;
}
.card {
.shadows(0 1px 2px #d1d5db, 0 4px 12px #e5e7eb;);
}.card {
box-shadow: 0 1px 2px #d1d5db, 0 4px 12px #e5e7eb;
}The semicolon at the end of the call tells Less: the commas inside are part of the value, not argument separators.
Common mistake
Without the trailing semicolon Less treats each shadow as a separate argument and joins them with a space:
// styles/main.less
.shadows(@list...) {
box-shadow: @list;
}
.card {
.shadows(0 1px 2px #d1d5db, 0 4px 12px #e5e7eb);
}.card {
box-shadow: 0 1px 2px #d1d5db 0 4px 12px #e5e7eb;
}The comma is gone, and the browser will drop the invalid box-shadow value. When you pass a comma-separated list, put ; at the end of the call.