Article: Mastering Less Guards and Loops

Extract from SitePoint article “Mastering Less Guards and Loops” by Ivaylo Gerchev

Published July 2, 2015

In the previous article we learned the basics of the Less mixin guards and loops. We saw that once we’ve gained a clear understanding of their structure we can use them properly. Now, we’ll explore how this knowledge can be put to practice by examining some real world examples.

Creating Alert Boxes

The first example is to create an alert box with four variations. We’ll create a mixin guard that transforms a regular div into a differently styled alert box – depending on the argument (the type of alert box) we pass to the mixin. First, we need to define some variables:

@color_info: #00a8e6;
@color_success: #8cc14c;
@color_warning: #faa732;
@color_error: #da314b;

These are four color variables, which we’re going to use for the four variants of our alert box. Now, let’s add the needed mixin guards:

.alert(@mode) when (@mode = 'info'){
  background-color: @color_info;
  border: thin solid darken(@color_info, 15%);
.alert(@mode) {
  width: 300px;
  padding: 25px;
  color: #fff;
  text-shadow: 0.5px 0.5px #000;

The first part of the above code creates a conditional statement, which, if the @mode parameter is equal to “info”, will use the @color_info variable to set both the background color of the alert box and the color for its border. We use the darken() function to make the border color 15% darker than the background color.

We need to repeat the same pattern for the rest three variants. We do that by copying and pasting the first variant. For each variant we use the appropriate color variable and change the word “info” to “success”, “warning”, and “error” respectively.

Finally, at the end, we put the styles that are common for all alert boxes. We set the text color to white and apply a subtle text shadow effect to it for better contrast.

Now, to use the mixin we need to put it like so .alert('success'), inside a CSS rule for the div. Et voila. We can see a nice alert box with green background.

Depending on our needs, we can use different colors for our alert boxes – by changing the values of the color variables – and still keeping the mixin semantic.

Continue reading article on SitePoint ….

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.