BEM CSS命名规范

引言

BEM, meaning Block, Element, Modifier, is a front-end methodology coined by developers working at Yandex. Whilst BEM is a complete methodology, here we are only concerned with its naming convention. Further, the naming convention here only is BEM-like; the principles are exactly the same, but the actual syntax differs slightly.

BEM splits components’ classes into three groups:

Block: The sole root of the component.
Element: A component part of the Block.
Modifier: A variant or extension of the Block.
CSS Guidelines

CSS不好维护,因为在项目中存在各种各样的CSS命名格式,ID、标签、层级等等,为了重用、语义化、避免冲突,CSS命名五花八门,造成CSS文件冗烂。自从看了张鑫旭大牛的文章精简高效的CSS命名准则方法才知道CSS渲染元素和使用JavaScript获取页面元素那是完全不一样的,CSS的渲染方式是从右往左渲染的。
.test span{} 这种命名方式举例,会先渲染页面上所有的span标签,然后再寻找test类的标签。所以,CSS命名,只要出现了层级,出现了标签,就是一次额外的渲染,层级越多,渲染的开销也就越大,这就是为什么一些前辈的文章会建议要尽量避免过深的层级。这也是为什么要“无层级”,“无标签”。

BEM命名

BEM是由老毛子的Yandex提出的一种CSS命名规范,是 Block-Element-Modifier 的缩写,
block:模块或者组件,名字单词间用 - 连接
element:元素,模块的子元素,以 __ 与 block 连接
modifier:修饰,模块的变体,表示不同的状态,以 – 与 block 连接
类似这种写法:

1
2
3
.block{}
.block__element{}
.block--modifier{}

在一个block下无论element的层级如何,都要扁平化,只能出现B__E–M最多三级,如果出现B__E-parent__E-child–M这种拖沓冗长的命名,就背离了BEM的初衷了。
BEM规范让CSS和html开起来结构清晰、有效提高CSS代码的重用率、易维护,并且能加快页面渲染,应该说是目前最受欢迎的一种命名规范,但是也受到好多大牛的诟病如何看待 CSS 中 BEM 的命名方式?
最近我在使用VUE组件库Element UI做开发,看了的源码,发现其中的CSS规范也是遵循BEM的。
例如:
alert组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.el-alert__title {
font-size: 13px;
line-height: 18px
}
.el-alert__description {
color: #fff;
font-size: 12px;
margin: 5px 0 0
}
.el-alert--success {
background-color: #13ce66
}

.el-alert--info {
background-color: #50bfff
}
/*没有采用.el-alert__icon--big、.el-alert__icon--bold这种写法,估计是考虑到类名太长吧 */
.el-alert__icon .is-big {
font-size: 28px;
width: 28px
}
.el-alert__title .is-bold {
font-weight: 700
}