縮寫核心價值
- 減少檔案體積 (Gzip 後效果更明顯)
- 提升可讀性:相關屬性聚合、減少重複選擇器
- 維護效率:修改一處生效多屬性
1. 顏色縮寫
/* 6 位十六進位 → 3 位 (每兩位相同時) */
#000000 → #000
#336699 → #369
#ff0000 → #f00
#abcdef → 無法縮寫 (各位不同)
/* 8 位 (含透明度) → 4 位 */
#ff0000ff → #f00f
#336699aa → #369a
2. 盒模型縮寫
/* 四值順時針:上 右 下 左 */
margin: 1rem; /* 四邊同值 */
margin: 1rem 2rem; /* 上下 1rem,左右 2rem */
margin: 1rem 2rem 3rem; /* 上 1rem,左右 2rem,下 3rem */
margin: 1rem 2rem 3rem 4rem; /* 上右下左 */
padding: 1em 0 2em 0.5em; /* 實戰常見:上下非對稱 */
border-width: 1px 2px 3px 4px; /* 同理適用 */
border-radius: 4px 8px 12px 16px; /* 左上 右上 右下 左下 */
3. 邊框縮寫
/* 順序:寬度 樣式 顏色 (順序不嚴格,但建議固定) */
border: 1px solid #000;
border-top: 2px dashed red;
border-radius: 4px 8px 0 0; /* 四角半徑 */
/* 邊框圖片 (進階) */
border: 10px solid transparent;
border-image: url(border.png) 30 round;
4. 背景縮寫
/* 順序:顏色 圖片 重複 附著 位置 */
background: #f00 url(bg.jpg) no-repeat fixed center top;
/* 多重背景 (逗號分隔,第一層最上層) */
background:
url(pattern.png) repeat,
url(hero.jpg) no-repeat center / cover,
linear-gradient(45deg, #fff, #f0f0f0);
/* 關鍵:背景色必須在最後一層 */
background: url(img.png) no-repeat center, #f0f0f0; /* ✓ */
background: #f0f0f0, url(img.png) no-repeat center; /* ✗ 色塊會蓋住圖片 */
5. 字體縮寫
/* 必須順序:style variant weight size/line-height family */
font: italic small-caps bold 1rem/1.5 "Noto Sans TC", sans-serif;
/* 最小必要:size/line-height family */
font: 1rem/1.5 sans-serif;
/* 系統字體關鍵字 */
font: caption; /* 系統標題字體 */
font: icon; /* 系統圖示字體 */
font: menu; /* 系統選單字體 */
font: message-box; /* 系統對話框字體 */
font: small-caption; /* 系統小標籤字體 */
font: status-bar; /* 系統狀態列字體 */
6. 列表縮寫
/* 順序:type position image */
list-style: square inside url(bullet.png);
/* 取消預設樣式 */
list-style: none;
/* 等同於 */
list-style-type: none;
list-style-position: outside;
list-style-image: none;
避坑指南
- 背景色必須在最後,否則蓋住圖片
- 字體縮寫必含 size + family,否則無效
- 縮寫會重置未指定屬性為預設值:
background: url() 會重置 color、repeat、position 等
- 邊框樣式預設為 none,
border: 1px solid red 缺 style 則不顯示