掌握 CSS 縮寫屬性,不僅能大幅減小文件體積,更能提升代碼可讀性與維護效率。本文系統梳理 6 大類核心屬性的縮寫規則、語法順序、默認值陷阱與實戰技巧,附帶速查表,建議收藏備查。
當每兩位值相同時,可縮寫為 3 位:
#000000 → #000
#336699 → #369
#FFA500 → #FA0 /* 非成對值無法縮寫 */
遵循**順時針順序:上 → 右 → 下 → 左**,支持 1-4 個值:
| 值個數 | 含義 | 記憶口訣 |
|---|---|---|
| 1 | 四邊相同 | 全同 |
| 2 | 上下 / 左右 | 上下、左右 |
| 3 | 上 / 左右 / 下 | 上、橫、下 |
| 4 | 上 / 右 / 下 / 左 | 順時針:上右下左 |
margin: 1em 0 2em 0.5em; /* 上1em 右0 下2em 左0.5em */
padding: 10px 20px; /* 上下10px 左右20px */
/* 長寫 */
border-width: 1px;
border-style: solid;
border-color: #000;
/* 縮寫:寬度 風格 顏色 */
border: 1px solid #000;
順序固定:width style color,不可亂序。可單獨縮寫單邊:border-left: 2px dashed red;
/* 長寫 */
background-color: #f00;
background-image: url(bg.gif);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
/* 縮寫:顏色 圖片 重複 固定 位置 */
background: #f00 url(bg.gif) no-repeat fixed 0 0;
默認值陷阱: 省略的屬性會重置為默認值(transparent / none / repeat / scroll / 0% 0%),非累加覆蓋。建議**只縮寫需改變的屬性**,或使用長寫避免意外重置。
/* 長寫 */
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1em;
line-height: 140%;
font-family: "Lucida Grande", sans-serif;
/* 縮寫:style variant weight size/line-height family */
font: italic small-caps bold 1em/140% "Lucida Grande", sans-serif;
硬性規定: 至少必須包含 font-size 與 font-family,否則聲明無效。line-height 需緊跟 font-size 以斜槓分隔。
/* 長寫 */
list-style-type: square;
list-style-position: inside;
list-style-image: url(img.gif);
/* 縮寫:type position image */
list-style: square inside url(img.gif);
快速重置:list-style: none; 移除默認項目符號與編號。
| 屬性類別 | 縮寫屬性 | 值順序 | 關鍵提示 |
|---|---|---|---|
| 顏色 | color / background-color 等 | #RGB 或 #RRGGBB | 成對值才能縮寫 |
| 盒模型 | margin / padding / border-width | 上 右 下左 (順時針) | 1-4值自動匹配 |
| 邊框 | border / border-top 等 | width style color | 順序固定 |
| 背景 | background | color image repeat attachment position | 省略即重置默認值 |
| 字體 | font | style variant weight size/line-height family | size+family必填 |
| 列表 | list-style | type position image | none可一鍵清除 |
熟練運用縮寫,配合 CSS 變量與模組化架構,能讓樣式表體積減少 30%+,閱讀效率提升數倍。下次寫 CSS 時,有意識地練習縮寫思維,養成「先想縮寫再寫長寫」的肌肉記憶。