Using Guard Expressions in Less Mixins for Conditional CSS
Learn how Less guard expressions let you write mixins that emit CSS only when conditions are met, reducing duplication and keeping your stylesheets clean.
10 Mar 2026, 10:35 UTC

Problem: Avoiding Duplicate CSS
When building a site you often need the same styling tweak for several breakpoints, themes, or component states. Writing a separate rule for each case leads to duplicated code and makes future changes error‑prone.
What Guard Expressions Are
Guard expressions let a Less mixin include or skip its CSS based on a boolean test evaluated at compile time. The when keyword follows the mixin name and is followed by any expression that resolves to true or false.
Syntax Basics
A guarded mixin looks like this:
.my-mixin(@arg) when (@arg > 0) {
width: @arg * 1px;
}
If the guard evaluates to true, the block is emitted; otherwise the mixin produces nothing. Multiple guards can be stacked, and the first matching guard wins.
Worked Example: Responsive Breakpoint Mixin
Suppose you want a helper that adds a left margin only on screens wider than a given breakpoint. Define a mixin that guards on a breakpoint variable:
@break-md: 768px;
.margin-left-when-wide(@width) when (@break-md >= @width) {
margin-left: @width;
}
/* Usage */
.container {
.margin-left-when-wide(24px);
}
Compile with:
lessc styles.less styles.css
Assuming Less 3.0 or newer, the generated CSS will be:
.container {
margin-left: 24px;
}
If you change @break-md to 600px, the guard fails and the output omits the margin rule entirely.
Trade‑offs and Limitations
- Guard ordering matters: a later guard that also matches will never be reached if an earlier one already matched.
- Complex boolean expressions (nested
and/or) were parsed inconsistently in releases before Less 3.0; using simple comparisons avoids surprises. - Guards are evaluated only at compile time; they cannot react to runtime changes like viewport resizing.
Actionable Next Steps
- Install Less 3.0+ (e.g.,
npm i -g less) if you haven’t already. - Add a guarded mixin for a pattern you repeat across breakpoints or themes.
- Compile your stylesheet and inspect the output to confirm only the intended rules appear.
- When extending the mixin, place the most specific guard first to keep the logic clear.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.