HTML & CSS
Article

Mastering Less Guards and Loops

By Ivaylo Gerchev

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.

See the Pen Mastering Less Guards and Loops #1 by SitePoint (@SitePoint) on CodePen.

Creating Responsive Grids

One of the most valuable uses of Less loops is for creating a responsive grid system. Let’s see how this can be done. Let’s explore the following code:

@breakpoint-small : 480px;
@breakpoint-medium: 768px;
@breakpoint-large : 960px;

.grid(@breakpoint; @columns; @index: 1) when (@index =< @columns) {

  .col-@{breakpoint}-1-@{index} {
    width: 100% / @index;
  }

  .grid(breakpoint; @columns; (@index + 1));
}

First, we have set three variables for different breakpoints. Then, we create the actual mixin. To output the needed CSS classes, we need two things – the breakpoint and the number of the columns for our grid. We set those as parameters in our mixin. Next, we create the pattern for the CSS rule. We want a pattern that tells us the actual width of a column.

Many frameworks define a column width by using the number of default columns (most often there are 12 default columns) that span. For example, for creating three equal columns they use .col-4 class for each column. But this can be confusing and not a sensible naming convention. It looks like they may want to create four columns instead of one. So, we’ll use a different approach, which I consider more natural. We’ll define our columns like this: col-1-3. This tell us that the column width is one third of the container’s width, which makes much more sense, at least for me.

To apply this pattern in our mixin, we just need to use the @screen_size and the @index variables, and also, to divide the @index by 100% for the width property. Lastly, we add the mixin itself, which will increment the @index by 1.

And now, let’s see how easy we can create different CSS classes for our grid:

.grid(all, 4);

@media only screen and (min-width: @breakpoint-small) {

  .grid(small, 4);

}

@media only screen and (min-width: @breakpoint-medium) {

  .grid(medium, 4);

}

@media only screen and (min-width: @breakpoint-large) {

  .grid(large, 4);

}

The first appearance of the .grid() mixin creates column classes applicable for all screen sizes. In the next three, we use media queries to generate column classes for our small, medium and large breakpoints. Let’s check the compiled output:

.col-all-1-1 {
  width: 100%;
}
.col-all-1-2 {
  width: 50%;
}
.col-all-1-3 {
  width: 33.33333333%;
}
.col-all-1-4 {
  width: 25%;
}
@media only screen and (min-width: 480px) {
  .col-small-1-1 {
    width: 100%;
  }
  ...
}
@media only screen and (min-width: 768px) {
  .col-medium-1-1 {
    width: 100%;
  }
  ...
}
@media only screen and (min-width: 960px) {
  .col-large-1-1 {
    width: 100%;
  }
  ...
}

Nice and useful CSS classes created on the fly. Thanks Less.

Generating CSS for Your Sprite Images

Imagine that we have a nice sprite image, which contains many icons. To make this sprite work, we need to write a lot of CSS – a separate rule for each icon, with the icons name and different background position. Doing this manually can be time consuming, especially if the image contains too many icons. In such a case, a Less loop is the ideal candidate for the job. Let’s explore how to create it:

@icons: tag flag filter sort sort-asc sort-desc;

.sprites(@length; @index: 1) when (@index =< @length) {

  @name: extract(@icons, @index);
  .icon-@{name} {
    background-position: 0 (@index * 32px);
  }

  .sprites(@length; (@index + 1));
}

.sprites(length(@icons));

We create the mixin with parameter @length, and @index set to 1. Then, we instruct the loop to iterate until the @index is equal to or lesser than the list’s length. Inside the loop’s body, we use the extract() function to get the name for each individual icon. Next, we create the desired CSS rule by using the @name and @index variables. And finally, we put the mixin itself to make the loop working.

Now, the only effort required from us is to put the names of the icons in a list, which the loop will use – as this is done in the first line of the above code.

To use the mixin, we just need to provide the length of the list, which we easily do by using the length() function. We don’t want to count the number of icons manually, right? :)

And here is the code generated by our mixin:

.icon-tag {
  background-position: 0 32px;
}
.icon-flag {
  background-position: 0 64px;
}
...
}
.icon-sort-desc {
  background-position: 0 192px;
}

Summary

I hope you’ve enjoyed the examples and have found them useful. Lots of things can be done with Less mixins and guards, and this article only scratches the surface. You now, hopefully, know the basic scheme and should be able to confidently experiment with your own ideas.

  • http://madalenagalbiati.com.br Madalena Galbiati

    I wonder if it’s possible to remove the repeating properties of the ‘modes’. Maybe pass the state name and concatenate it on the end of @colour_ ? Anyone knows if it can be done?

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.