Less
02 / 02

Guards, Recursion & Legacy Considerations

Guards, Recursion & Legacy Considerations

Guards — Less's Conditional Logic

// Less has no plain @if/@else statement — conditionals attach to mixins
.theme(@name) when (@name = dark) {
  background: black;
  color: white;
}
.theme(@name) when (@name = light) {
  background: white;
  color: black;
}

Recursive Mixins (Looping)

// No native @for loop — generate a numbered scale via recursion + a guard
.generate-margins(@n, @i: 1) when (@i =< @n) {
  .m-@{i} { margin: @i * 4px; }
  .generate-margins(@n, @i + 1);  // recursive call, decrementing toward the guard
}
.generate-margins(5);  // produces .m-1 through .m-5

!important on a Mixin Call

.button-reset() {
  background: none;
  border: none;
  padding: 0;
}

// Applies !important to EVERY declaration the mixin outputs —
// handy when overriding a third-party component library's styles
.my-button {
  .button-reset() !important;
}

Compiling & Lazy Variable Resolution

lessc input.less output.css
lessc --watch input.less output.css

Less resolves a variable based on its LAST definition within the applicable scope at the point of use — not strict top-to-bottom order like most general-purpose languages. This "lazy loading" behavior can surprise developers expecting sequential assignment, and is worth knowing before debugging an unexpected variable value inside a mixin.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free