任何超過(guò) 1000 行的 CSS 代碼,你都曾經(jīng)歷過(guò)這樣的體驗(yàn):
xxoo
class,會(huì)造成沖突嗎?Reasonable System for CSS Stylesheet Structure
的目標(biāo)就是解決以上問(wèn)題,它不是一個(gè)框架,而是通過(guò)規(guī)范,讓你構(gòu)建更健壯和可維護(hù)的 CSS 代碼。
從 Components
的角度思考,將網(wǎng)站的模塊都作為一個(gè)獨(dú)立的 Components
。
Components
最少以兩個(gè)單詞命名,通過(guò) -
分離,例如:
.like-button
).search-form
).article-card
)Elements
是 Components
中的元素
Elements
的類名應(yīng)盡可能僅有一個(gè)單詞。
.search-form {
> .field { /* ... */ }
> .action { /* ... */ }
}
對(duì)于倘若需要兩個(gè)或以上單詞表達(dá)的 Elements
類名,不應(yīng)使用中劃線和下劃線連接,應(yīng)直接連接。
.profile-box {
> .firstname { /* ... */ }
> .lastname { /* ... */ }
> .avatar { /* ... */ }
}
任何時(shí)候盡可能使用 classnames
。標(biāo)簽選擇器在使用上沒(méi)有問(wèn)題,但是其性能上稍弱,并且表意不明確。
.article-card {
> h3 { /* ? avoid */ }
> .name { /* ? better */ }
}
Components
和 Elements
可能都會(huì)擁有 Variants
。
Variants
的 classname
應(yīng)帶有前綴中劃線 -
.like-button {
&.-wide { /* ... */ }
&.-short { /* ... */ }
&.-disabled { /* ... */ }
}
.shopping-card {
> .title { /* ... */ }
> .title.-small { /* ... */ }
}
為什么使用中劃線作為變體的前綴?
Elements
_
或 -
開(kāi)頭Components 應(yīng)該在不同的上下文中都可以復(fù)用,所以應(yīng)避免設(shè)置以下屬性:
頭像和 logos 這些元素應(yīng)該設(shè)置固定尺寸(寬度,高度...)。
倘若你需要為組件設(shè)置定位,應(yīng)將在組件的上下文(父元素)中進(jìn)行處理,比如以下例子中,將 widths
和 floats
應(yīng)用在 list component(.article-list)
當(dāng)中,而不是 component(.article-card)
自身。
.article-list {
& {
@include clearfix;
}
> .article-card {
width: 33.3%;
float: left;
}
}
.article-card {
& { /* ... */ }
> .image { /* ... */ }
> .title { /* ... */ }
> .category { /* ... */ }
}
當(dāng)出現(xiàn)多個(gè)嵌套的時(shí)候容易失去控制,應(yīng)保持不超過(guò)一個(gè)嵌套。
/* ? Avoid: 3 levels of nesting */
.image-frame {
> .description {
/* ... */
> .icon {
/* ... */
}
}
}
/* ? Better: 2 levels */
.image-frame {
> .description { /* ... */ }
> .description > .icon { /* ... */ }
}
-
是一坨糟糕的玩意:其實(shí)你可以選擇性的使用,只要將 Components, Elements, Variants
記在心上即可。aleter
。但其實(shí)你可以使用后綴,使其意識(shí)更加明確。比如塊級(jí)元素:
或行內(nèi)級(jí)元素
RSCSS 與其他 CSS 模塊組織系統(tǒng)相似的概念
RSCSS | BEM | SMACSS |
---|---|---|
Component | Block | Module |
Element | Element | ? |
Layout | ? | Layout |
Variant | Modifier | Theme & State |
Components
的角度思考,以兩個(gè)單詞命名(.screenshot-image
)Components
中的 Elements
,以一個(gè)單詞命名(.blog-post .title
)Variants
,以中劃線-
作為前綴(.shop-banner.-with-icon
)Components
可以互相嵌套記住,你可以通過(guò)繼承讓事情變得更簡(jiǎn)單
更多建議: