Mixins in LESS are simply classes with a specified property that is reusable. They are similar to functions in programming languages.
We can declare a Mixin the same way we declare a class or ID selector in CSS. It can store multiple values that can be reused later in the development as necessary.
.my-mixin {
color: red;
}
A Mixin is called with the parenthesis, similar to the way a function is called in a programming language.
p{
.my-mixin();
}
The code above will have the color red once it’s compiled to CSS.
The output will be as follows:
p{
color: red;
}
A Mixin that is declared with a parenthesis will not appear in the output CSS. This means if we wish for the Mixin to work but don’t want it to show in our CSS file, we to declare it with parenthesis.
For example, consider the following input:
.my-first-mixin{
color: #fff;
}
.my-other-mixin(){
font-size: 10px;
}
h1{
my-first-mixin();
my-other-mixin();
}
The output will be without the other Mixin, as follows:
.my-first-mixin{
color: #fff;
}
h1{
color: #fff;
font-size: 10px;
}
A Mixin is not limited to containing just properties. It can hold other selectors too.
For example, consider the following input:
.my-mixin(){
&:hover{
color: #000;
font-size: 1.75em;
}
a{
.my-mixin();
}
Note: The Mixin above contains a pseudo-class that is reusable later in the code.
The output is as follows:
a:hover{
color: #000;
font-size: 1.75em;
}
The mixin will not appear in our output file because it was declared with the parenthesis.
A Mixin can be declared with an argument, just like functions in programming languages. This can be achieved by simply declaring a variable inside the parenthesis, and later using it as a value inside the Mixin.
For example, consider the following input:
.my-mixin ( @width: 70%; @bg: #f4f4f4 ) {
background-color: @bg;
width: @width;
}
div{
.my-mixin();
}
This will result in the following:
div{
background-color: #f4f4f4;
width: 70%
}
Using the important
keyword after a Mixin will mark all its properties as important when used.
For example, consider the following input:
.my-mixin{
color: red;
}
p{
.my-mixin() !important;
}
The output is as follows:
.my-mixin{
color: red;
}
p{
color: red !important;
}