Dreamweaver 等視覺化工具產出的 CSS 往往冗長。掌握縮寫規則,能讓樣式表體積縮減 30-50%,並提升瀏覽器解析速度。
| 屬性類別 | 冗長寫法 | 縮寫寫法 | 關鍵規則 |
|---|---|---|---|
| 零值單位 | padding: 10px 5px 0px 0px; | padding: 10px 5px 0 0; | 值為 0 時省略單位 |
| 移除多餘選擇器 | div#logowrap | #logowrap | id 唯一,標籤限定多餘 |
| 通配符 * 限域使用 | * { margin:0; } | #menu * { margin:0; } | 限制範圍避免全域汙染 |
| background 綜合 | 分行寫 image/position/repeat | background: url(logo.png) no-repeat top center; | 順序:color image repeat position |
| 顏色值縮寫 | #000000 #336699 | #000 #369 | 三組重複十六進位各取一碼 |
| margin/padding 顺时针 | 四行分別宣告 | margin: 0 10px 0 10px; → margin: 0 10px; | 上右下左;上下/左右相等再縮為兩值 |
| border 綜合 | 分行寫 width/style/color | border: 1px solid #000; | 順序:width style color |
| border 邊別寬度 | 四行寫 top/right/bottom/left | border-width: 1px 2px 3px 4px; | 顺时针 |
| font 綜合 | 六行分別宣告 | font: italic small-caps bold 1em/150% "Microsoft JhengHei", sans-serif; | 順序:style variant weight size/line-height family;size 與 family 必填 |
| list-style 綜合 | 三行分別宣告 | list-style: square inside url(bullet.gif); | 順序:type position image |
將縮寫規則內化為肌肉記憶,並配合建構工具(PostCSS、cssnano)自動化優化,持續保持 CSS 代碼庫精簡高效。