善用 CSS 縮寫可大幅縮減檔案體積並統一風格。以下整理顏色、盒模型、邊框、背景、字體、列表六大類常用縮寫語法與順序口訣。
16 進位色碼若每兩位相同,可縮寫為 3 碼:
#000000 → #000#336699 → #369#ABCDEF → 無法縮寫順時針順序:上 → 右 → 下 → 左 (Top, Right, Bottom, Left)
| 寫法 | 值個數 | 對應方向 | 範例 |
|---|---|---|---|
margin: 10px; | 1 | 上右下左皆 10px | 全部相同 |
margin: 10px 20px; | 2 | 上下 10px、左右 20px | 垂直/水平不同 |
margin: 10px 20px 30px; | 3 | 上 10px、左右 20px、下 30px | 上下不同、左右相同 |
margin: 10px 20px 30px 40px; | 4 | 上 10、右 20、下 30、左 40 | 四邊各異 |
/* 分開寫 */
border-width: 1px;
border-style: solid;
border-color: #000;
/* 縮寫:寬度 樣式 顏色 */
border: 1px solid #000;
單邊縮寫:border-top: 2px dashed red;
/* 分開寫 */
background-color: #f00;
background-image: url(bg.png);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: left top;
/* 縮寫順序:顏色 圖片 重複 附著 位置 */
background: #f00 url(bg.png) no-repeat fixed left top;
/* 預設值:transparent none repeat scroll 0% 0% */
/* 分開寫 */
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1em;
line-height: 1.4;
font-family: "Microsoft JhengHei", sans-serif;
/* 縮寫:style variant weight size/line-height family */
/* 必須包含 font-size 與 font-family,其餘可省略 */
font: italic small-caps bold 1em/1.4 "Microsoft JhengHei", sans-serif;
/* 分開寫 */
list-style-type: square;
list-style-position: inside;
list-style-image: url(bullet.png);
/* 縮寫:type position image */
list-style: square inside url(bullet.png);
/* 移除預設符號 */
list-style: none;