BEM

15 阅读1分钟

1. 简介

BEM(Block、Element、Modifier)是前端样式管理中最经典、最持久的命名规范之一。

它的目标是:

  • 让 CSS 命名有语义、无冲突、可维护、可复用。
缩写含义说明
BBlock模块(组件)本身,是独立、可复用的功能单元
EElement模块内部的组成部分(依附于 Block)
MModifier模块或元素的修饰状态(颜色、尺寸、样式变化等)

2. 基本命名规则

BEM 的核心是 命名结构清晰且有层级关系

.block {}
.block__element {}
.block--modifier {}

即:

  • “双下划线 __” 表示 属于某个 Block 的 Element
  • “双短横线 --” 表示 某个 Block 或 Element 的 Modifier

3. 示例

以一个按钮组件为例:

3.1. html 结构
<button class="button button--primary">
  <span class="button__icon"></span>
  <span class="button__label">提交</span>
</button>

✅ 每个类名都有清晰语义:
.button 是模块、
.button__icon 是子元素、
.button--primary 是状态修饰。

3.2. 对应 CSS:
/* Block */
.button {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
} 

/* Modifier */
.button--primary {
  background-color: #1890ff;
  color: #fff;
}

.button--danger {
  background-color: #ff4d4f;
}

/* Element */
.button__icon {
  margin-right: 4px;
}
3.3. SCSS 写法:
/* Block */
.button {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;

  /* Modifier */
  &--primary {
    background-color: #1890ff;
    color: #fff;
  }

  &--danger {
    background-color: #ff4d4f;
  }

  /* Element */
  &__icon {
    margin-right: 4px;
  }
}