CSS的组件化方案:OOCSS + BEM
CSS由于缺少命名空间,所有的class都是全局的,所以大团队项目如果没有良好的命名规范,会容易失控。
举例实现以下效果:
通过 class + tag
.pageButtons {
display: flex;
justify-content: center;
}
.pageButtons button{
width: 80px;
height: 30px;
margin: 5px;
border-radius: 4px;
border: none;
font-size:13px;
cursor: pointer;
outline: none;
}
.primary-button {
color: white;
background-color: rgba(200,0,0,.9);
transition: background-color 1s,font-weight 1s;
}
.primary-button:hover {
font-weight: 700;
background-color: rgba(255,0,0,1);
}
<div class="pageButtons">
<button>
Previous
</button>
<button>
Next
</button>
<button class="primary-button">
Next
</button>
</div>
想象下,把此页面(或者做成组件)嵌入到另外一个页面,而它也以button 标签定义了button的样式,会造成非我们期望的button样式。所以尽量避免标签定义样式。还有一个问题是,.primary-button看似是一个普通的类,也有可能在别的地方定义,所以维护会比较困难。
通过 OOCSS + BEM实现
OOCSS就是通过选择符重用CSS类。BEM全称Block-name__element--modifier.
.pageButtons {
display: flex;
justify-content: center;
}
.pageButtons__prev,
.pageButtons__next,
.pageButtons__next--primary {
width: 80px;
height: 30px;
margin: 5px;
border-radius: 4px;
border: none;
font-size:13px;
cursor: pointer;
outline: none;
}
.pageButtons__next--primary {
color: white;
background-color: rgba(200,0,0,.9);
transition: background-color 1s,font-weight 1s;
}
.pageButtons__next--primary:hover {
font-weight: 700;
background-color: rgba(255,0,0,1);
}
<div class="pageButtons">
<button class="pageButtons__prev">
Previous
</button>
<button class="pageButtons__next">
Next
</button>
<button class="pageButtons__next--primary">
Next
</button>
</div>
相对于前种方案,BEM命名比较冗长,但这正是保证CSS类名不会重复的途径,是BEM的核心思想。
通过OOSCSS
如果用SASS写:
%button {
width: 80px;
height: 30px;
margin: 5px;
border-radius: 4px;
border: none;
font-size:13px;
cursor: pointer;
outline: none;
}
%primaryState {
color: white;
background-color: rgba(200,0,0,.9);
transition: background-color 1s,font-weight 1s;
}
%hoverState {
font-weight: 700;
background-color: rgba(255,0,0,1);
}
.pageButtons {
display: flex;
justify-content: center;
&__prev,
&__next,
&__next--primary {
@extend %button;
}
&__next--primary {
@extend %primaryState;
}
&__next--primary:hover {
@extend %hoverState;
}
}
这里稍提下%placeHolder 和 @mixin,如果不用传人参数,用%placeHoder,这样可以以选择符重用类,相对于@mixin复制代码,减少了代码体积。