CSS – BEM (Block__Element--Modifier)


前言

BEM 是一种 CSS class 命名规范. 目的是防止大家名字取太短, 不小撞名字后果很麻烦.

参考:

Youtube – You Probably Need BEM CSS in Your Life (Tutorial)

Battling BEM CSS: 10 Common Problems And How To Avoid Them

结构

<section class="service-section">
  <h1 class="service-section__title">Service 1h1>
  <p class="service-section__description">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae,
    omnis.
  p>
  <button class="service-section__action service-section__action--focused">
    click
  button>
section>

Block

block 就是一个 namespace 概念, 算是全局命名了, 要确保与页面里其它 block 不能撞,

Element

element 就是元素的语义命名, 比如 title, description, call to action 对比 h1, p, button

有些人不喜欢拿 semantic HTML 来做 selector 所以就有了更语义化的 element.

要确保在整个 block 里面, element 名字不能撞哦.

Modifier

modifier 通常用来表达状态 state, 比如 focused, hovered, 变种 element 的意思.

Sass 结构

.service-section {
  &__title {
    color: red;
  }
  &__description {
    font-size: 1.5rem;
  }
  &__action {
    text-transform: uppercase;
    letter-spacing: 1px;
    padding: 0.5rem 1rem;

    &--focused {
      background-color: rgba($color: blue, $alpha: 0.3);
    }
  }
}

利用嵌套和 & 语法, 虽然 class name 很长, 但 Sass 并没有重复的代码, 看上去还可以. 

常见问题 FAQ:

问: 如果有很多层, 是不是要写成 block__element1_element2_modifier 还是 block1_block2_element_modifier? 

答: no, BEM 的结构永远都是 block-name__element-name--modifier, block name, element name 可以用 kebab-case 写长长, 防止撞名字.

相关