CSS因为缺乏命名空间,全部的class都是全局的,因此大团队项目若是没有良好的命名规范,会容易失控。flex
举例实现如下效果:spa
.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看似是一个普通的类,也有可能在别的地方定义,因此维护会比较困难。code
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的核心思想。element
若是用SASS写:it
%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复制代码,减小了代码体积。io