Benjaming 🔨

記錄自己的學習旅程

0%

BEM

接觸開發到現在對於 html class 命名並沒有特別研究,有幸得到前輩的指導,於是紀錄一下自己研讀的過程

What is BEM ?

BEM 是一種 CSS class 命名的設計模式,將介面切割成許多獨立的區塊,以區塊(Block)、元素(Element)和修飾子(Modifier)來命名,優點是以元件觀念進行開發,具有重用性。 它擁有 OOCSS 的架構清楚的美好,也沒有 SMACSS 複雜或令人混淆的部份,因此 BEM 是一個很優秀的 CSS 架構指南。

How to use ?

假設今天預計要做出以下的 Button:

用一般的方式命名通常會用下列方式,這樣的缺點是規則缺乏通用準則,無法馬上理解 Class 之間彼此的相依性,也很容易與其他 Class 命名衝突。

1
2
3
4
5
6
7
8
9
10
11
<div>
<button class="button">
Normal button
</button>
<button class="button success">
Success button
</button>
<button class="button danger">
Danger button
</button>
</div>

若採用 BEM 模式 加上 Block Element Modifier :

1
2
3
4
5
6
7
8
9
10
11
<div class="toolbox">
<button class="toolbox__button">
Normal button
</button>
<button class="toolbox__button toolbox__button--success">
Success button
</button>
<button class="toolbox__button toolbox__button--danger">
Danger button
</button>
</div>

於是便能很快地知道 toolbox 是Block, toolbox__button是 Element, toolbox__button--success 是 Element 的其中一個狀態

以 vue 的 Element UI 為例,也是採用 BEM 的方式來命名,前面多了el Name Space,常見的 Name Space 參考

1
2
3
4
<button type="button" class="el-button el-button--warning"></button>
<button type="button" class="el-button el-button--primary"></button>
<button type="button" class="el-button el-button--success"></button>
<button type="button" class="el-button el-button--info"></button>