Parametric mixins

In the tutorial Styling with LESS we saw that LESS Mixins are classes that can be mixed into other classes. This is especially time saving when we use a class containing several lines of code and mix that in to define another class.

Parametric Mixins give us flexibility. We can use the same rule set to define another class but customize it in different situations with the parameter(s).

Basic parametric mixin

An example of a basic parametric mixin from the Bootstrap 3 file “mixins.less” is:

The mixin .border-top-radius has the parameter @radius instead of a constant value.

This mixin is used several times in the Bootstrap 3 LESS files. One example of its use is from the “button-groups.less” file:

In this instance we specify that the first and last button in a vertical button group must have a border radius but with a value zero.

Variable defines value of parametric mixin

We can also use a variable as a parameter in a mixin.

We see an example of this in the Bootstrap 3 file “list-group.less”:

In this example the variable @list-group-border-radius is used as the parameter in the mixin .border-top-radius.

When we look for the variable @list-group-border-radius in the file “variables.less” we see that it is defined by yet another variable:

Seems like a complicated way to set a value. The advantage of doing it this way is that we can remain consistent. Each time we use this mixin we know that the same value is being used. At the same time we gain the advantage that changing this value needs only to be done in one location.

If we do want to change the value for the border radius we only have to do so in the “variables.less” file. We have 2 options to do this:

  1. We can specifically set a different value for the border radius of list groups. With the LESS files we can do this by creating a copy of the “variables.less” file and overriding the @list-group-border-radius variable:
  2. Or – if you prefer to remain consistent and use the same border radius for the other components – you can achieve this with:

In our next tutorial about LESS parametric mixins we go one step further and set default values for the parameters.

Add your comment