樣式表寫久了,總會想把冗長的宣告壓成一行。以下把最常縮寫的幾組屬性與規則整理成速查表。
十六進位色值若每兩位相同,可以縮寫成三位:
#000000 → #000 #336699 → #369
反之若兩位不相同就不能縮,例如 #FC1A1B 必須寫滿六位。
完整寫法:
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: font-style | font-variant | font-weight | font-size | line-height | font-family。要注意的是,縮寫時 font-size 與 font-family 兩者至少必須出現其一,否則整條宣告會失效。
完整寫法:
background-color: #f00; background-image: url(background.gif); background-repeat: no-repeat; background-attachment: fixed; background-position: 0 0;
縮寫成:
background: #f00 url(background.gif) no-repeat fixed 0 0;
語法為 background: color image repeat attachment position。省略的項目會取瀏覽器預設值:
color: transparent; image: none; repeat: repeat; attachment: scroll; position: 0% 0%;
list-style-type: square; list-style-position: inside; list-style-image: url(image.gif);
縮寫成:
list-style: square inside url(image.gif);
要拿掉預設的項目符號與編號,寫 list-style: none; 即可。
border-width: 1px; border-style: solid; border-color: #000;
縮寫成:
border: 1px solid #000;
語法為 border: width style color。同理,border-top、border-bottom 等單側邊框也適用相同順序。
這類屬性有四種書寫形式:
property: value1; /* 四邊同值 */ property: value1 value2; /* 上下 = value1,左右 = value2 */ property: value1 value2 value3; /* 上、左右、下 */ property: value1 value2 value3 value4; /* 依序為上、右、下、左 */
記憶方式是順時針:上、右、下、左。實際例子:
margin: 1em 0 2em 0.5em;
還有一個常被忽略的簡化:若左右兩值相同、上下兩值相同,就能從四值壓成兩值;若三值裡左右相同,就壓成三值。反過來說,只有「上與下相同、左右不同」或「上右下各不相同」時,才真的需要寫滿。