
本文讲解在遵循 BEM 命名规范的前提下,利用 Sass 的嵌套与 & 运算符批量生成跨块(如 .section1__title 和 .section2__title)的共享样式,避免重复代码,兼顾语义性与可维护性。
本文讲解在遵循 bem 命名规范的前提下,利用 sass 的嵌套与 `&` 运算符批量生成跨块(如 `.section1__title` 和 `.section2__title`)的共享样式,避免重复代码,兼顾语义性与可维护性。
在 BEM(Block-Element-Modifier)方法论中,每个块(Block)应保持语义独立、样式解耦,但现实中常存在多个块需共用某类元素样式的情况——例如 .section1__title 和 .section2__title 在视觉上完全一致。若机械地按块分别编写嵌套规则:
.section1 {
&__title { font-size: 2rem; font-weight: bold; color: #333; }
}
.section2 {
&__title { font-size: 2rem; font-weight: bold; color: #333; } // ❌ 重复!
}
不仅违背 DRY(Don’t Repeat Yourself)原则,更增加后期维护成本。
✅ 正确做法是:将具有共性样式的块选择器合并书写,并借助 Sass 的 & 实现智能拼接:
.section1,
.section2 {
// 公共块级样式(可选)
padding: 2rem 0;
background-color: #f9f9f9;
&__title {
font-size: 2rem;
font-weight: bold;
color: #333;
margin-bottom: 1rem;
}
&__subtitle {
font-size: 1.25rem;
color: #666;
}
&__content {
line-height: 1.6;
}
}
编译后将精准输出符合 BEM 规范的 CSS:
.section1, .section2 {
padding: 2rem 0;
background-color: #f9f9f9;
}
.section1__title, .section2__title {
font-size: 2rem;
font-weight: bold;
color: #333;
margin-bottom: 1rem;
}
.section1__subtitle, .section2__subtitle { /* ... */ }
.section1__content, .section2__content { /* ... */ }
⚠️ 注意事项:
- 此方式仅适用于语义合理且样式真正一致的跨块元素。若 .section1__title 后期需差异化(如加图标、换色),应拆分为独立规则或引入 Modifier(如 .section1__title--featured),而非强行复用;
- 避免过度合并(如 .section1, .section2, .hero, .card, .banner {...}),会降低可读性与定位效率——建议按功能/场景分组,例如 section-layout, feature-block 等语义化组合;
- 若共享逻辑复杂(含媒体查询、伪类等),可进一步封装为 Sass @mixin,再配合 @include 调用,实现更高阶复用。
总结:BEM 不排斥样式复用,关键在于通过选择器组合 + Sass 机制,在不破坏命名约束的前提下提升开发效率。合并父选择器并善用 &,正是 BEM 与 Sass 协同的最佳实践之一。










