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