善用 CSS 縮寫屬性能大幅精簡程式碼,降低檔案大小並提升維護性。以下為各類常用屬性的縮寫規則與記憶技巧。
十六進制顏色若每兩位相同,可縮寫為三碼:
#000000 → #000#336699 → #369| 寫法 | 對應邊界 |
|---|---|
value1 | 四邊同值 |
value1 value2 | 上下 / 左右 |
value1 value2 value3 | 上 / 左右 / 下 |
value1 value2 value3 value4 | 上 / 右 / 下 / 左 |
適用屬性:margin、padding、border-width 等。
/* 分開寫 */
border-width: 1px;
border-style: solid;
border-color: #000;
/* 合併 */
border: 1px solid #000; /* 語法:width style color */
background: #f00 url(bg.gif) no-repeat fixed 0 0;
/* 語法:color image repeat attachment position */
省略值將採用瀏覽器預設:transparent / none / repeat / scroll / 0% 0%。
font: italic small-caps bold 1em/140% "Lucida Grande", sans-serif;
/* 順序:style variant weight size/line-height family */
注意:font-size 與 font-family 為必填,否則 Firefox 會失效。錯誤範例:font: 700 14px/22px;(缺 family)。
list-style: square inside url(image.gif);
/* type position image */
outline 類似 border 但不佔版面空間,語法相同:outline: 1px solid red;margin: 0; 而非 margin: 0px;#logowrap 優於 div#logowrap。* 慎用,建議限制範圍:#menu * { margin: 0; }。.login_top { height:26px; font:bold 14px/26px "宋體"; border:1px solid #000 }
.login_top2 { height:26px; line-height:26px; font-weight:bold; font-size:14px; border:1px solid #000; font-family:'宋體' }
第一行縮寫版不僅簡潔,且能確保 line-height 與 height 一致,讓單行文字垂直置中。