縮寫三大核心效益量化
| 維度 | 量化指標 | 典型提升 |
| 檔案體積 | Gzip 前後 bytes | 減少 15-30% (配合 Gzip 更顯著) |
| 解析速度 | 瀏覽器 CSSOM 建立時間 | 規則數減少 → 解析快 5-10% |
| 維護效率 | 修改點數量 / Code Review 時間 | 單點修改生效多屬性、Diff 行數減 40% |
實戰對比:縮寫前後
/* ❌ 展開寫法:12 行、280 字符 */
.list-item {
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2rem;
line-height: 1.4;
padding-top: 5px;
padding-bottom: 10px;
padding-left: 5px;
padding-right: 0;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
margin-right: 0;
}
/* ✅ 縮寫後:4 行、120 字符 (減 57%) */
.list-item {
font: 1.2rem/1.4 Arial, Helvetica, sans-serif;
padding: 5px 0 10px 5px;
margin: 0;
}
六大縮寫類別完整速查表
| 類別 | 縮寫屬性 | 展開屬性 (順序固定) | 關鍵規則 |
| 字體 | font | style → variant → weight → size/line-height → family | 必含 size + family,否則無效 |
| 背景 | background | color → image → repeat → attachment → position | 色值必須在最後,多背景逗號分隔 |
| 邊框 | border | width → style → color | style 必寫 (預設 none 不顯示) |
| 外邊距/內邊距 | margin/padding | 1值/2值/3值/4值 (順時針: 上右下左) | 邏輯屬性 margin-block/inline 更現代 |
| 列表 | list-style | type → position → image | none 重置所有 |
| 顏色 | #rgb/#rgba | 每兩位相同可縮寫 | 8位含透明度 |
現代 CSS 新增縮寫
/* 邏輯屬性縮寫 (書寫模式感知) */
margin-block: 1rem 2rem; /* margin-top + margin-bottom */
margin-inline: 1rem 2rem; /* margin-left + margin-right (LTR) */
padding-block: 1rem; /* padding-top + padding-bottom */
inset-block: 10px 20px; /* top + bottom */
inset-inline: 15px; /* left + right */
border-block: 1px solid #000; /* border-top + border-bottom */
border-inline: 2px dashed red; /* border-left + border-right */
border-radius: 4px 8px 0 0; /* 物理角 */
border-start-start-radius: 4px; /* 邏輯角 */
/* 動畫縮寫 */
animation: name 1s ease 0s 1 normal forwards;
transition: all 0.3s ease;
/* Grid 縮寫 */
grid: "header header" auto "main aside" 1fr / 250px 1fr;
/* Flex 項目 */
flex: 1 1 300px; /* grow shrink basis */
避坑:縮寫隱性重置
/* 背景色會被 background 縮寫重置為 transparent */
.card {
background-color: #fff;
background: url(pattern.png); /* ❌ 背景色消失! */
}
/* 正確 */
.card {
background: #fff url(pattern.png) repeat;
}
/* 邊框樣式預設 none */
.box {
border-width: 2px;
border-color: red;
/* border: 2px red; ❌ 缺 style 不顯示 */
border: 2px solid red; /* ✅ */
}
團隊規範建議
- 簡單規則 (≤3 屬性) 可單行縮寫
- 複雜規則展開寫,但相關屬性必須用縮寫 (如 margin/padding)
- 背景、字體、動畫、Grid/Flex 善用縮寫
- Stylelint 強制:
"shorthand-property-no-redundant-values": true