對比兩段代碼:
/* 亂序:找 margin-right 需掃視 7 行 */
.h1 { z-index:101; color:#000; position:relative; line-height:24px; margin-right:48px; border-bottom:1px solid #dedede; font-size:18px; }
/* 字母序:二分查找直達 margin-right */
.h1 { border-bottom:1px solid #dedede; color:#000; font-size:18px; line-height:24px; margin-right:48px; position:relative; z-index:101; }
字母序優勢:
| 反駁 | 回應 |
|---|---|
| 「邏輯分組更符合思維」 | 現代編輯器支援「折疊/區域」,邏輯分組靠註釋區塊實現,非靠屬性順序 |
| 「相關屬性應聚合」 | 字母序下 margin-*、padding-*、border-* 自然聚合 |
| 「CSS-in-JS 不需要」 | 樣式對象屬性順序同樣影響 Diff 可讀性,建議統一字母序 |
/* stylelint.config.js */
module.exports = {
plugins: ['stylelint-order'],
rules: {
'order/properties-alphabetical-order': true,
'order/order': ['custom-properties', 'declarations']
}
};
Prettier 亦可配置 "cssDeclarationSorter": true(需插件)。
--custom-prop 排在最前(Stylelint custom-properties 規則)@media、@supports 內部同樣執行字母序