Less Guard是编译期分支,用于决定mixin是否匹配执行;必须写在mixin末尾、用when引导,支持=、!=、<、>等比较及and/or/not逻辑,但严格区分类型与单位,不支持运行时切换。

Less Guard守卫的基本写法和触发条件
Guard不是JavaScript里的if,它只在编译期起作用,用于决定某个mixin是否匹配、是否执行。关键点在于:Guard必须写在mixin定义末尾,用when关键字引导,括号内是布尔表达式,且只支持有限的比较操作(=、!=、<、>、=<、>=),不支持&&或||直接拼接——得用嵌套或逗号分隔多个条件。
.border-style(@type) when (@type = solid) {
border-style: solid;
}
.border-style(@type) when (@type = dashed) {
border-style: dashed;
}
.border-style(@type) when (@type = none) {
border-style: none;
}
注意:Less会按顺序尝试匹配,第一个满足Guard的mixin生效,后续同名但条件不满足的会被跳过。
多个条件怎么写:用逗号代替逻辑与
Less Guard里没有&&,但可以用逗号表示“所有条件都需为真”。比如想限定只有当@size大于2px且@color是#000时才输出粗黑边框:
.thick-black-border(@size, @color) when (@size > 2px), (@color = #000) {
border: @size solid @color;
}
⚠️ 这里逗号是“或”逻辑(Less 3.5+ 之后的语义);真正表示“且”的写法是把多个条件写在同一组括号里:
立即学习“前端免费学习笔记(深入)”;
.thick-black-border(@size, @color) when (@size > 2px) and (@color = #000) {
border: @size solid @color;
}
and、or、not 是Less内置逻辑关键字,必须小写,且只能出现在when括号内。
Guard常见失效原因:类型不匹配和单位陷阱
Less做Guard比较时严格区分类型和单位。下面这行永远不会匹配成功:
.text-size(@n) when (@n = 14) { font-size: @n; }
// 调用 .text-size(14px); → 不匹配!因为 14px ≠ 14
-
14是数字,14px是带单位的值,二者类型不同 - 解决办法:统一用
isnumber()或ispixel()等类型判断函数,或提前剥离单位
.text-size(@n) when (ispixel(@n)) and (@n = 14px) {
font-size: @n;
}
.text-size(@n) when (isnumber(@n)) and (@n = 14) {
font-size: @n * 1px;
}
其他易错点:
- 字符串比较必须加引号:
@theme = "dark",不能写@theme = dark(后者被当变量) -
null和未定义变量在Guard中通常报错,建议用isdefined()兜底
实际项目中推荐的Guard组织方式
别把所有分支堆在一个mixin名下。复杂逻辑建议拆成带语义的子mixin,再由主mixin调度:
.btn-variant(@style) when (@style = primary) { .btn-primary(); }
.btn-variant(@style) when (@style = secondary) { .btn-secondary(); }
.btn-variant(@style) when (@style = danger) { .btn-danger(); }
<p>.btn-primary() {
background: #007bff;
color: white;
}</p>这样既保持可读性,又避免Guard嵌套过深导致编译失败或难以调试。另外,Guard不支持运行时动态切换——它只在Less编译成CSS那一刻起作用,生成的CSS里不会留下任何条件逻辑。
Less Guard本质是“编译期分支”,不是“运行时样式开关”。如果需要响应式或用户交互切换,得靠CSS类名切换或JavaScript配合,Guard帮不上忙。


















