less
  1. less-parametric-mixins

Parametric Mixins - (Less Mixins)

Less is a popular CSS preprocessor that provides various features to make it easier to write CSS code. One of its features is mixins, which allow you to define a group of CSS properties and reuse them throughout your code. In this tutorial, we'll discuss parametric mixins in Less, which allow you to create mixins with parameters.

Syntax

.mixin-name(@parameter1: value1, @parameter2: value2) {
  property1: @parameter1;
  property2: @parameter2;
}

You can then use the mixin by calling it with the desired parameter values:

.selector {
  .mixin-name(parameter1-value, parameter2-value);
}

Example

Let's create a parametric mixin that sets the font size and font weight of text:

.text-properties(@font-size: 14px, @font-weight: normal) {
    font-size: @font-size;
    font-weight: @font-weight;
}

We can then use this mixin in our code:

.my-class {
    .text-properties(16px, bold);
}

The output CSS will be:

.my-class {
    font-size: 16px;
    font-weight: bold;
}

Explanation

In this example, we created a parametric mixin called .text-properties that takes two parameters: @font-size and @font-weight. These parameters have default values of 14px and normal, respectively.

We then used the .text-properties mixin in our .my-class selector, passing in the values 16px for the font size parameter and bold for the font weight parameter. The mixin replaces the parameter values in the properties it generates, resulting in the output CSS that sets the font size and font weight of .my-class.

Use

Parametric mixins in Less are useful because they allow you to create reusable sets of CSS properties with different parameter values. This can save you time and reduce code duplication.

You can use parametric mixins to create sets of properties for specific use cases, such as text styles, button styles, or form input styles. You can also use them to create utility classes that you can apply to any element in your code.

Important Points

  • You can define a default value for a mixin parameter by specifying it after the parameter name separated by a colon.
  • Mixins can take any number of parameters, and their values can be any valid Less expression.
  • You can use mixin parameters in any property value or property name within the mixin's block.

Summary

In this tutorial, we discussed parametric mixins in Less, which allow you to create mixins with parameters. We covered the syntax, example, explanation, use cases, and important points of parametric mixins. With this knowledge, you can start using parametric mixins in your Less code to create reusable sets of CSS properties.

Published on: