模塊組織
模塊組織
任何超過 1000 行的 CSS 代碼,你都曾經(jīng)歷過這樣的體驗:
1.這個 class 到底是什么意思呢?
2.這個 class 在哪里被使用呢?
3.如果我創(chuàng)建一個 xxoo
class,會造成沖突嗎?
Reasonable System for CSS Stylesheet Structure
的目標就是解決以上問題,它不是一個框架,而是通過規(guī)范,讓你構建更健壯和可維護的 CSS 代碼。
Components(組件)
從 Components
的角度思考,將網(wǎng)站的模塊都作為一個獨立的 Components
。
Naming components (組件命名)
Components
最少以兩個單詞命名,通過 -
分離,例如:
- 點贊按鈕 (
.like-button
) - 搜索框 (
.search-form
) - 文章卡片 (
.article-card
)
Elements (元素)
Elements
是 Components
中的元素
Naming elements (元素命名)
Elements
的類名應盡可能僅有一個單詞。
.search-form { > .field { /* ... */ } > .action { /* ... */ } }
On multiple words (多個單詞)
對于倘若需要兩個或以上單詞表達的 Elements
類名,不應使用中劃線和下劃線連接,應直接連接。
.profile-box { > .firstname { /* ... */ } > .lastname { /* ... */ } > .avatar { /* ... */ } }
Avoid tag selectors (避免標簽選擇器)
任何時候盡可能使用 classnames
。標簽選擇器在使用上沒有問題,但是其性能上稍弱,并且表意不明確。
.article-card { > h3 { /* ? avoid */ } > .name { /* ? better */ } }
Variants (變體)
Components
和 Elements
可能都會擁有 Variants
。
Naming variants (變體命名)
Variants
的 classname
應帶有前綴中劃線 -
.like-button { &.-wide { /* ... */ } &.-short { /* ... */ } &.-disabled { /* ... */ } }
Element variants (元素變體)
.shopping-card { > .title { /* ... */ } > .title.-small { /* ... */ } }
Dash prefixes (中劃線前綴)
為什么使用中劃線作為變體的前綴?
- 它可以避免歧義與
Elements
- CSS class 僅能以單詞和
_
或-
開頭 - 中劃線比下劃線更容易輸出
Layout (布局)
Avoid positioning properties (避免定位屬性)
Components 應該在不同的上下文中都可以復用,所以應避免設置以下屬性:
Positioning (position, top, left, right, bottom)
Floats (float, clear)
Margins (margin)
Dimensions (width, height) *
Fixed dimensions (固定尺寸)
頭像和 logos 這些元素應該設置固定尺寸(寬度,高度...)。
Define positioning in parents (在父元素中設置定位)
倘若你需要為組件設置定位,應將在組件的上下文(父元素)中進行處理,比如以下例子中,將 widths
和 floats
應用在 list component(.article-list)
當中,而不是 component(.article-card)
自身。
.article-list { & { @include clearfix; } > .article-card { width: 33.3%; float: left; } } .article-card { & { /* ... */ } > .image { /* ... */ } > .title { /* ... */ } > .category { /* ... */ } }
Avoid over-nesting (避免過分嵌套)
當出現(xiàn)多個嵌套的時候容易失去控制,應保持不超過一個嵌套。
/* ? Avoid: 3 levels of nesting */ .image-frame { > .description { /* ... */ > .icon { /* ... */ } } } /* ? Better: 2 levels */ .image-frame { > .description { /* ... */ } > .description > .icon { /* ... */ } }
Apprehensions (顧慮)
中劃線
-
是一坨糟糕的玩意:其實你可以選擇性的使用,只要將Components, Elements, Variants
記在心上即可。我有時候想不出兩個單詞唉:有些組件的確使用一個單詞就能表意,比如 aleter 。但其實你可以使用后綴,使其意識更加明確。
比如塊級元素:
.alert-box
.alert-card
.alert-block
或行內(nèi)級元素
.link-button
.link-span
Terminologies (術語)
RSCSS 與其他 CSS 模塊組織系統(tǒng)相似的概念
Summary (總結)
以
Components
的角度思考,以兩個單詞命名(.screenshot-image
)Components
中的Elements
,以一個單詞命名(.blog-post .title
)Variants
,以中劃線-作為前綴(.shop-banner.-with-icon
)Components
可以互相嵌套記住,你可以通過繼承讓事情變得更簡單
- *