logo头像

arthas.com.cn

CSS中的BEM规范

该文章被围观

本文于437天之前发表,文中内容可能已经过时。

BEM代表 “块(block),元素(element),修饰符(modifier)”

  • block: 页面是由多个block构成的,跟其他的block区分开来
  • element:并不是简单的父子关系,在区块中担负的职责,取唯一性的名字
  • modifier:状态的修改

以微信的weui组件库中的tabbar组件为例:

tabbar.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./weui.css">
<link rel="stylesheet" href="./tabbar.css">
</head>
<body>
<div class="weui-tabbar">
<a href="#" class="weui-tabbar__item">
<span>
<img class="weui-tabbar__icon weui-tabbar__icon_on" src="./icon/icon_tabbar.png" alt="">
<span class="weui-badge">1</span>
</span>
<p class="weui-tabbar__label">微信</p>
</a>
<a href="#" class="weui-tabbar__item">
<span>
<img class="weui-tabbar__icon" src="./icon/icon_tabbar.png" alt="">
<span class="weui-badge"></span>
</span>
<p class="weui-tabbar__label">微信</p>
</a>
<a href="#" class="weui-tabbar__item">
<span>
<img class="weui-tabbar__icon" src="./icon/icon_tabbar.png" alt="">
<span class="weui-badge"></span>
</span>
<p class="weui-tabbar__label">微信</p>
</a>
<a href="#" class="weui-tabbar__item">
<span>
<img class="weui-tabbar__icon" src="./icon/icon_tabbar.png" alt="">
<span class="weui-badge"></span>
</span>
<p class="weui-tabbar__label">微信</p>
</a>
</div>
</body>
</html>
  • weui-tabbar表示block
  • weui-tabbar__item、weui-tabbar__icon中的__item和_icon表示element
  • weui-tabbar__icon_on中的_on表示modifier,即元素的状态

weui.css:

1
2
3
4
5
6
* {
margin: 0;
padding: 0;
-webkit-user-select: none;
user-select: none;
}

tabbar.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
.weui-tabbar {
display: flex;
position: absolute;
bottom: 0;
width: 100%;
z-index: 500;
background-color: #f7f7fa;
}
.weui-tabbar__item {
flex: 1;
text-align: center;
padding: 5px 0 0 0;
font-size: 0;
color: #808080;
}
.weui-tabbar__item > span {
display: inline-block;
position: relative;
}
.weui-tabbar__icon {
display: inline-block;
width: 27px;
height: 27px;
}
.weui-badge {
position: absolute;
top: -2px;
right: -13px;
min-width: 8px;
display: inline-block;
padding: .15em .4em;
font-size: 12px;
line-height: 12px;
background-color: #f43539;
border-radius: 18px;
color: #ffffff;
}
.weui-tabbar__label {
font-size: 10px;
color: #808080;
text-align: center;
/* 此处的行高是相对于字体大小的比例,即字体的1.8倍 */
line-height: 1.8;
}
上一篇