less虽无内置bem支持,但可通过嵌套、&运算符和参数化mixin实现可控、可复用的bem类名生成,如.button__text、.button--primary;需避免漏写&导致后代选择器、重复写modifier时用.bem-modifier封装、禁止跨block嵌套及过度嵌套,并注意css modules下class名hash对动态绑定的影响。

Less 本身不内置 BEM 支持,但通过嵌套、变量和参数化混合(parametric mixins),能写出接近 BEM 语义又不冗余的代码。关键不是“模拟 BEM 语法”,而是让 .block__element--modifier 的生成可控、可复用、不污染全局选择器。
用嵌套 + & 运算符拼出标准 BEM 类名
Less 的 & 表示父选择器,配合嵌套是生成 BEM 类名最直接的方式。注意:必须显式写出 &,否则编译后会变成后代选择器而非连缀类名。
.button {
// block
&__text {
font-size: 14px;
}
&__icon {
display: inline-block;
}
&--primary {
background: #007bff;
}
&--small {
padding: 4px 8px;
}
}
编译结果是:.button__text、.button__icon、.button--primary —— 完全符合 BEM 规范。常见错误是漏写 &,比如写成 __text,结果会编译成 .button __text(空格 → 后代选择器)。
抽离 modifier 混合避免重复写 &--xxx
当多个 block 都需要同类 modifier(如 --disabled、--hover),硬编码 &--disabled 会重复。用参数化 mixin 封装更干净:
.bem-modifier(@modifier) {
&--@{modifier} {
@{arguments};
}
}
.button {
.bem-modifier(disabled) {
opacity: 0.5;
cursor: not-allowed;
}
.bem-modifier(hover) when (not (@_)) {
&:hover {
background: darken(#007bff, 10%);
}
}
}
这里 @{arguments} 允许传入任意样式声明;when (not (@_)) 是 Less 的“非空判断”,防止无参数调用时生成空规则。注意:mixin 内部的 & 仍指向调用它的父选择器,所以 .bem-modifier(disabled) 在 .button 下展开后仍是 .button--disabled。
Miller (mlr) 是一个命令行工具,用于查询、整形和重新格式化名称索引数据,如 CSV、TSV、JSON 和 JSON Lines。它将 awk、sed、cut、join 和 sort 的功能整合到一个专为结构化数据处理而构建的单一工具中。
避免嵌套过深导致选择器爆炸
BEM 要求扁平,但 Less 嵌套容易无意中写出三级以上选择器,比如 &__item &__link 编译成 .list__item .list__link(带空格 → 后代),这违背 BEM “每个类名独立可识别” 的原则。
- 只在真正需要修饰 element 或 modifier 时才用
&__xxx或&--xxx - 禁止跨 block 嵌套,例如不要在
.header里写.footer__logo - 如果必须组合(如
.button--primary .button__text),显式写出两个类名:.button--primary &__text,而不是靠嵌套推导
过度嵌套还会拖慢 Less 编译速度,尤其在大型项目中。
与 CSS Modules 或现代构建工具共存时的注意事项
如果你项目已用 Webpack + css-loader?modules 或 Vue 的 scoped,Less 里的 BEM 类名会被自动 hash(如 .button__text_abc123)。此时手动写的 &__text 依然生效,但要注意:
- JavaScript 中获取 class 名需用
styles['button__text']而非字面量'button__text' - 第三方组件(如 Ant Design)的 BEM 类名不会被 hash,不能和你本地的 BEM 规则混用
&去覆盖 - 如果启用了
localIdentName自定义 hash 格式,确保它不破坏 BEM 结构(比如别把下划线转成连字符)
真正麻烦的是动态 class 绑定 —— class="button__text {{ isBold ? 'button__text--bold' : '' }}" 这种写法在 hash 后失效,得改用 :class="{ [styles['button__text--bold']]: isBold }"。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










