「代碼是給人讀的,順便能在機器上跑。」CSS 作為聲明式語言,易讀性直接決定維護成本。本文從格式化風格、屬性排序、註釋規範三個維度,構建團隊級 CSS 可讀性標準。
/* 派系 A:展開式(每屬性一行) - 推薦團隊協作 */
.selector {
background-color: #3399cc;
color: #666;
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
height: 300px;
margin: 10px 5px;
padding: 5px 0 10px 5px;
width: 30%;
z-index: 10;
}
/* 派系 B:緊湊式(單行) - 適合屬性極少/生產環境輸出 */
.selector { background-color: #3399cc; color: #666; font: 1.2em/1.4em Arial; height: 300px; margin: 10px 5px; padding: 5px 0 10px 5px; width: 30%; z-index: 10; }
.complex {
background-image:
linear-gradient(#000, #ccc),
linear-gradient(#ccc, #ddd);
box-shadow:
2px 2px 2px #000,
1px 4px 1px 1px #ddd inset;
}
**不要靠人工約束**,接入格式化工具:
| 維度 | 字母序 (A-Z) | 功能分組 |
|---|---|---|
| 查找速度 | ⭐⭐⭐⭐⭐ (二分查找) | ⭐⭐⭐ (需記住分組邏輯) |
| 認知負荷 | 低(無需記憶) | 高(需團隊共識分組標準) |
| 相關屬性聚合 | 差(margin/padding 分離) | 優(盒模型/字體/視覺/定位分組) |
| 工具支持 | Stylelint 內建 `order: "alphabetical"` | 需自定義插件/配置 |
採用字母序作為基準,**關鍵佈局屬性前置**(`display`, `position`, `flex/grid` 相關),兼顧查找效率與語義聚合:
.card {
/* 佈局優先 */
display: flex;
flex-direction: column;
position: relative;
z-index: 1;
/* 字母序其餘 */
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,.1);
color: #333;
margin: 16px;
padding: 24px;
width: 100%;
}
Stylelint 配置:
{
"plugins": ["stylelint-order"],
"rules": {
"order/order": [
["display", "position", "top", "right", "bottom", "left", "z-index", "flex*", "grid*"],
{ "order": "alphabetical" }
]
}
}
/*=============================================
= 1. 文件級:目錄結構 =
=============================================*/
/**
* @file button.css
* @description 按鈕組件樣式
* @author Zhang San
* @version 1.2.0
*/
/*=============================================
= 2. 區塊級:模塊分隔 =
=============================================*/
/* ----- 基礎樣式 ----- */
.btn { ... }
/* ----- 狀態變體 ----- */
.btn--primary { ... }
.btn--disabled { ... }
/* ----- 尺寸變體 ----- */
.btn--sm { ... }
.btn--lg { ... }
/*=============================================
= 3. 行級:關鍵邏輯說明 =
=============================================*/
.btn::before {
content: '';
/* 使用偽元素實現邊框動畫,避免觸發重排 */
position: absolute;
inset: -2px;
border: 2px solid currentColor;
transform: scale(0);
transition: transform 0.2s ease;
}
/** @section Layout **/
.grid { ... }
/** @component Card **/
.card { ... }
/** @utility Spacing **/
.mt-16 { margin-top: 1rem; }
/* IDE 搜尋 @section/@component/@utility 即可快速定位 */
可讀性不是審美偏好,是**工程契約**。統一格式化消除無意義 diff,科學排序加速認知檢索,分級註釋傳遞設計意圖——三位一體,讓 CSS 代碼真正成為團隊資產而非負債。