LESS Mixins

LESS Mixins eliminate the need of writing repeatable CSS by allowing you to re-use portions of code within your project. The basic principals of mixins is that you define some CSS properties within the mixin declaration, and then call the mixin in the CSS classes that you want to use the properties for.

The most common CSS property that could require a mixin is border-radius. The original CSS for this includes the properties for the different CSS rendering engines of different browsers (-webkit, -moz). Therefore we might have a rule that looks like the following:

.border {
    -webkit-border-radius: 5px; 
    -moz-border-radius: 5px; 
    -ms-border-radius: 5px;
    border-radius: 5px;
}

Define a Mixin

To define a mixin, you simple define a CSS rule that you would when writing normal CSS.

.custom-border {
    -webkit-border-radius: 5px; 
    -moz-border-radius: 5px; 
    -ms-border-radius: 5px;
    border-radius: 5px;
}

You can then include this rule in another rule.

.container {
    .custom-border;
    font-size: 12px;
}

This will compile to the below CSS.

.custom-border {
    -webkit-border-radius: 5px; 
    -moz-border-radius: 5px; 
    -ms-border-radius: 5px;
    border-radius: 5px;
}

.container {
    -webkit-border-radius: 5px; 
    -moz-border-radius: 5px; 
    -ms-border-radius: 5px;
    border-radius: 5px;
    font-size: 12px;
}

Mixin Parameters

You can also pass in parameters to your mixin, if for example you want to use a different px value for border-radius. The parameters are prefixed with the @ symbol.

.custom-border(@radius) {
    -webkit-border-radius: @radius; 
    -moz-border-radius: @radius; 
    -ms-border-radius: @radius;
    border-radius: @radius;
}

Now our .container rule can specify the px value.

.container {
    .custom-border(3px);
    font-size: 12px;
}

The mixin definitions by default are included in the CSS output. If you do not wish to include them in the output, simply specify a pair of parentheses after defining the name.

.my-mixin {
    color: black;
}
.my-other-mixin() {
    background: white;
}
.class {
    .my-mixin;
    .my-other-mixin;
}

my-other-mixin will not be included in the output.

.my-mixin {
    color: black;
}

.class {
    color: black;
    background: white;
}

That concludes the basic overview of using LESS Mixins. They are a powerful feature enabling you to write less CSS and speed up your workflow.