title: CSS 样式命名头疼? 有个 BEM 命名规范了解一下?
date: 2022.09.23 19:46:03
tags:

  • 前端
  • CSS
  • 开发规范

categories:

  • 开发

0x0 BEM 背景是啥

BEM (Block, Element and Modifier) 是一种帮助在大型前端开发中创建可重用组件和代码共享的方法,由 Yandex 团队提出的一种前端 CSS 命名方法论。

BEM 说白了就是把样式按照 B E M 三种来进行命名。

0x01 BEM (Blocks, Elements and Modifiers) 是啥

B (Block)

B - Block 一个独立的模块,一个本身就有意义的独立实体 比如:header, container, menu, checkbox, input

E (Element)

E - Element 元素,块的一部分但是自身没有独立的含义 比如:menu item, list item, checkbox caption, header title

M (Modifier)

M - Modifier 修饰符,块或者元素的一些状态或者属性标志 比如:disabled, highlighted, checked, fixed, size big, color yellow

0x03 BEM 整點 🌰

1
2
3
4
5
6
7
8
9
<button class="button">
Normal button
</button>
<button class="button button--state-success">
Success button
</button>
<button class="button button--state-danger">
Danger button
</button>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.button {
display: inline-block;
border-radius: 3px;
padding: 7px 12px;
border: 1px solid #D5D5D5;
background-image: linear-gradient(#EEE, #DDD);
font: 700 13px/18px Helvetica, arial;
}
.button--state-success {
color: #FFF;
background: #569E3D linear-gradient(#79D858, #569E3D) repeat-x;
border-color: #4A993E;
}
.button--state-danger {
color: #900;
}

0x04 好处是啥

模块化

模块式的命名几乎不会依赖页面上的其它元素,避免级联的问题。

可复用

在一个标准指南中,每个独立的块都可以较为方便的复用。

结构简单

BEM 方法提供了一个简单,清晰易懂的结构。

0x06 日常结束的废话

我才不会感谢你的阅读呢,哼~不点个赞打个赏什么的嘛。

0x05 参考