sass-classname VS %placeholder

通过@extend 一个占位符,或者样式,都可以编译出一段CSS的代码片段,但是什么时候去调用更好呢?

1 @extend .className的不足

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.button {
display: block;
padding: 10px;
background: green;
}

.sidebar .signup .button {
margin-top: 20px;
}

.registrantion, .remember-password {
.button {
margin-bottom: 33px;
}
}

.edit-account .delete-area .button {
background-color: red;
color: white;
}

使用继承

1
2
3
.article a {
@extend .button;
}

编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.button, .article a {
display: block;
padding: 10px;
background: green;
}

.sidebar .signup .button, .sidebar .signup .article a, .article .sidebar .signup a {
margin-top: 20px;
}

.registrantion .button, .registrantion .article a, .article .registrantion a, .remember-password .button, .remember-password .article a, .article .remember-password a {
margin-bottom: 33px;
}

.edit-account .delete-area .button, .edit-account .delete-area .article a, .article .edit-account .delete-area a {
background-color: red;
color: white;
}

你可能只希望编译出这样的结果

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
.button, .article a {
display: block;
padding: 10px;
background: green;
}
``

为什么会出现这样的情况?

.button类名可能用在不同之处,有不同的容器包裹着,然而Sass中的@extend无法判断引用哪个地方的.button。所以他自己做主,将不同地方出现的.button类名都引入了进来。

2. 漂亮的%placeholder

```css
.button, %button {
display: block;
padding: 10px;
background: green;
}

.sidebar .signup .button {
margin-top: 20px;
}

.registrantion, .remember-password {
.button {
margin-bottom: 33px;
}
}

.edit-account .delete-area .button {
background-color: red;
color: white;
}

.article a {
@extend %button;
}

编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.button, .article a {
display: block;
padding: 10px;
background: green;
}

.sidebar .signup .button {
margin-top: 20px;
}

.registrantion .button, .remember-password .button {
margin-bottom: 33px;
}

.edit-account .delete-area .button {
background-color: red;
color: white;
}