縮寫能同時達到兩個目的:縮小 CSS 檔的體積,以及讓程式碼更易讀。以下是主要規則。
十六進位色碼若每兩位相同,可以縮寫一半:
#000000 → #000
#336699 → #369
margin 與 padding 有四種寫法:
property: value1; /* 四邊同值 */
property: value1 value2; /* 上下 value1,左右 value2 */
property: value1 value2 value3; /* 上 value1,左右 value2,下 value3 */
property: value1 value2 value3 value4; /* 依序為上、右、下、左 */
記憶方法是順時針方向:上、右、下、左。例如:
margin: 1em 0 2em 0.5em;
border-width: 1px;
border-style: solid;
border-color: #000;
可縮寫為一句,語法是 border: width style color;:
border: 1px solid #000;
background-color: #f00;
background-image: url(background.gif);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
語法是 background: color image repeat attachment position;:
background: #f00 url(background.gif) no-repeat fixed 0 0;
你可以省略其中一項或數項,被省略的屬性會改用瀏覽器預設值:
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1em;
line-height: 140%;
font-family: "Lucida Grande", sans-serif;
可縮寫為:
font: italic small-caps bold 1em/140% "Lucida Grande", sans-serif;
注意:縮寫字體時,至少要明確定義 font-size 與 font-family 兩項,否則整條規則會失效。
取消預設的項目符號與編號,寫 list-style: none; 即可。完整屬性如下:
list-style-type: square;
list-style-position: inside;
list-style-image: url(image.gif);
縮寫後為:
list-style: square inside url(image.gif);