LESS - Mixin Guards


Advertisements

Description

If you want to match simple values or number of arguments on expressions, then you can make use of guards. It is associated with mixin declaration and includes condition that is attached to a mixin. Each mixin will have one or more guards which are separated by comma; a guard must be enclosed within parentheses. LESS uses guarded mixins instead of if/else statements and performs calculations to specify matched mixin.

The following table describes the different types of mixins guards along with description.

Sr.No. Types & Description
1 Guard Comparison Operators

You can use the comparison operator (=) to compare numbers, strings, identifiers, etc.

2 Guard Logical Operators

You can use the and keyword to work around logical operators with guards.

3 Type Checking Functions

It contains the built-in functions to determine the value types for matching mixins.

4 Conditional Mixins

LESS uses the default function to match mixin with other mixing matches.

Example

The following example demonstrates the use of mixin guards in the LESS file −

<!doctype html>
   <head>
      <title>Mixin Guards</title>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <h2>Example of Mixin Guards</h2>
      <p class = "class1">Hello World...</p>
      <p class = "class2">Welcome to Howcodex...</p>
   </body>
</html>

Now, create the style.less file.

style.less

.mixin (@a) when (lightness(@a) >= 50%) {
   font-size: 14px;
}

.mixin (@a) when (lightness(@a) < 50%) {
   font-size: 16px;
}

.mixin (@a) {
   color: @a;
}

.class1 {
   .mixin(#FF0000)
}

.class2 {
   .mixin(#555)
}

You can compile the style.less to style.css by using the following command −

lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −

style.css

.class1 {
   font-size: 14px;
   color: #FF0000;
}

.class2 {
   font-size: 16px;
   color: #555;
}

Output

Follow these steps to see how the above code works −

  • Save the above html code in the mixin-guard.html file.

  • Open this HTML file in a browser, the following output will get displayed.

Mixin Guards
Advertisements