樣式表寫久了就會發現,屬性的排列順序與 class 命名其實會大幅影響後續維護成本。以下整理幾種主流主張,以及一套可落地的命名規則。
在 mozilla.org 的 Base Styles 中,作者 fantasai 列出了這樣的建議順序:
/* Suggested order: * display * list-style * position * float * clear * width * height * margin * padding * border * background * color * font * text-decoration * text-align * vertical-align * white-space * other text * content */
後續有人把這串屬性歸成三組:顯示屬性、自身屬性、文本屬性。也有觀點認為這與瀏覽器的解析過程有關:先對 DOM 定位,再解析自身屬性,最後處理內部物件。
需要澄清的是,Mozilla 官方並沒有正式推薦任何書寫順序。這個說法多半源自某位開發者讀 fantasai 文章時順手翻了她的 CSS 原始檔。
Trevor Davis 在《5 Ways to Instantly Write Better CSS》中主張屬性按字母排序。
優點是簡單,任何人遵守都能一眼看懂。缺點是太過機械、缺乏邏輯:像 position、left、top 這種關係密切的屬性被字母序拆散,撰寫與維護都不方便。
el {
display: ;
visibility: ;
float: ;
clear: ;
position: ;
top: ;
right: ;
bottom: ;
left: ;
z-index: ;
width: ;
min-width: ;
max-width: ;
height: ;
min-height: ;
max-height: ;
overflow: ;
margin: ;
margin-top: ;
margin-right: ;
margin-bottom: ;
margin-left: ;
padding: ;
padding-top: ;
padding-right: ;
padding-bottom: ;
padding-left: ;
border: ;
border-width: ;
border-style: ;
border-color: ;
outline: ;
list-style: ;
table-layout: ;
caption-side: ;
border-collapse: ;
border-spacing: ;
empty-cells: ;
font: ;
font-family: ;
font-size: ;
line-height: ;
font-weight: ;
text-align: ;
text-indent: ;
text-transform: ;
text-decoration: ;
letter-spacing: ;
word-spacing: ;
white-space: ;
vertical-align: ;
color: ;
background: ;
background-image: ;
background-repeat: ;
background-position: ;
opacity: ;
cursor: ;
content: ;
quotes: ;
}
這套順序大體與 fantasai 的主張一致,但細節更具可操作性。
fantasai 的順序中「自身屬性」定義有點含混,Andy 的又太細不易記。可以參考 CSS 2.1 規範的分類方式,調整成:
border: 1px solid red; 裡的 border-width 屬於盒模型,border-color 卻是裝飾性的。CSS 和其他程式語言一樣有作用域概念,分全域與類局部:
p{background:#f00;}/* 作用域:全域 */
.div p{color:#000;}/* 作用域:div 類中 */
幾種選擇器的權值對照:
最常見的錯誤是用版面位置命名,例如 left、right。當左欄不再位於左邊時,這個名字就失去意義,用序號命名問題更大。真正要避免的情況是:當狀態(表現)改變時,對應的類名不會失去意義。
所謂狀態改變有三種情形:
red、font14 這類描述外觀的名稱,必然出現名不符實。實務上這三種往往混雜出現,因此規則設計如下:
[模塊前綴]_類型_(作用|狀態)n_[位置n] * (必選):必需存在 [可選]:可根據需要選擇 |:多選一 n:可有多個
名詞說明:
約定事項:每項都可有自己的縮寫表,同一名稱的縮寫盡量統一;選詞應避免過於具體描述狀態(顏色、大小);由非數字開頭的小寫字母與數字組成;確保 class 的可重用性與 id 的唯一性,id 避免使用保留字。
模塊前綴:彈出 pop/公共 global,gb/標題 title,tit/提示 hint/菜單 menu/信息 info/預覽 pvw/Tips tips/導航 nav
類型:按鈕 bt/文本 tx/段落 p/圖標 icon/input input/顏色 color,c/背景 bg/邊框 bor
作用:設置 set/添加 add/刪除 del/操作 op/密碼 pw/導入 inc
狀態:成功 suc/失敗 lost/透明 tran
位置:公共 gb/邊框 bor/段落 p/彈出 pop/標題 title,tit/菜單 menu/內容 cont/導航 nav
.input_tx.input_pw.input_pw_login.c_tx.c_tx_p.pop_set_photo.hint_suc_blogset.hint_gb命名時其實只要連續問三個問題:
input。input_tx。input_search_index。結合模組化思維去定義,真正需要命名的名稱並不多。例如 hint_tx 表示提示模組的文字定義,hit_tx_hint 表示提示中文字強調的定義——至於是改顏色還是加粗,就交給各提示模組自行決定。