less Guards (for writing conditional mixins) Style an element based on a variable's value


Example

.set-colors(@type) when (@type = error) {
  @base-color: #d9534f;
  background: @base-color;
  color: contrast(@base-color, lighten(@base-color, 25%), darken(@base-color, 25%));
  border: 1px solid contrast(@base-color, lighten(@base-color, 25%), darken(@base-color, 25%));
}
.set-colors(@type) when (@type = info) {
  @base-color: #5bc0de;
  background: @base-color;
  color: contrast(@base-color, lighten(@base-color, 5%), darken(@base-color, 5%));
  border: 1px solid contrast(@base-color, lighten(@base-color, 5%), darken(@base-color, 5%));
}
.set-colors() {
  background: white;
  color: black;
  border: 1px solid black;
}

.error-message {
  .set-colors(error);
}
.info-message {
  .set-colors(info);
}
.default-div {
  .set-colors;
}

In the above example, the background, border and color are assigned based on the type of element. If the element is a default text div then the background will be white whereas the text and border would be black. If it is an "error" message display div or an "info" message display div then the colors are assigned based on the type.

The compiled CSS output would be as follows:

.error-message {
  background: #d9534f;
  color: #f0b9b8;
  border: 1px solid #f0b9b8;
}
.info-message {
  background: #5bc0de;
  color: #46b8da;
  border: 1px solid #46b8da;
}
.default-div {
  background: white;
  color: black;
  border: 1px solid black;
}