善用縮寫能有效縮小 CSS 檔的體積,也讓程式碼更容易讀。以下是幾個最常派上用場的規則。
十六進位色碼若每兩位相同,可以縮寫成一半:#000000 寫成 #000;#336699 寫成 #369。
有四種寫法:
● 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: 1px solid #000;
語法順序是 border: width style color;
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%
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);