Understanding Less Guards and Loops

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

The developers’ desire to bring features from programming to CSS led to creation of CSS preprocessors. They allow us to define variables and create functions just as we do so in JavaScript; but even more important, we can make our code more flexible by using conditional and iterating blocks.

Such blocks can be created using Less, but the syntax for their use is quite different from the traditional if…else and for patterns. In contrast to Sass and Stylus, Less tries to stick as close as it can to the original CSS. Therefore, to construct conditionals and loops, it uses syntax borrowed from media queries. This can be a bit confusing at first, but once we learn how it works, we will see that it’s just another way to say the same thing.

Less Mixin Guards

Less calls its conditional statements mixin guards. To construct a conditional block, we need to use mixins in conjunction with guards. Let’s demonstrate the main scheme with an example:

.theme (@mode) when (@mode = "dark") {
  background-color: darkblue;
}
.theme (@mode) when (@mode = "light") {
  background-color: lightblue;
}
 
div {
  width: 50px;
  height: 50px;
  .theme("light");
}

Continue reading this article on SitePoint …

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