熟練掌握 CSS 縮寫屬性,能讓樣式表體積縮減 30% 以上、可讀性大幅提升。本文彙整 5 大類最常用縮寫規則與順序口訣。
#000000 → #000、#336699 → #369、#f2f2f2 **不可縮寫** (f2 不重複)。#FFF = #FFFFFF = white、#06C = #0066CC。border: 1px solid #000;
/* width | style | color */
border-top: 2px dashed red; /* 單邊同理 */
margin: 1px 2px 3px 4px; /* 上 | 右 | 下 | 左 (順時針) */
margin: 1px 2px 3px; /* 上 | 左右 | 下 */
margin: 1px 2px; /* 上下 | 左右 */
margin: 1px; /* 四邊同值 */
padding: ... /* 規則完全相同 */
**口訣**:「上右下左」順時針,少值遞補對稱邊。
background: #f00 url(bg.gif) no-repeat fixed 0 0;
/* color | image | repeat | attachment | position */
等效全寫:
background-color: #f00;
background-image: url(bg.gif);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
font: italic small-caps bold 1em/140% "Lucida Grande", sans-serif;
/* style | variant | weight | size/line-height | family */
**必要條件**:至少包含 font-size 與 font-family,否則無效。
list-style: square inside url(bullet.gif);
/* type | position | image */
cssnano / clean-css 自動壓縮為最短縮寫。background 僅改顏色時,單獨寫 background-color 更清晰、不易誤覆蓋其他子屬性。