縮寫不只是少打幾個字,它同時能縮小檔案、讓宣告一目了然。以下是幾個高頻屬性的縮寫規則。
十六進位色碼若每兩位相同,可縮寫成三位:
#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: transparentimage: nonerepeat: repeatattachment: scrollposition: 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 兩者必須同時出現,否則整條宣告會被瀏覽器判定無效而忽略。這是最常踩的坑。line-height 緊跟在 font-size 之後,中間用斜線分隔。
取消預設的項目符號與編號:
list-style: none;
完整屬性:
list-style-type: square;
list-style-position: inside;
list-style-image: url(image.gif);
/* 縮寫後 */
list-style: square inside url(image.gif);
縮寫的原則是「同類屬性合併」,但別為了短而犧牲可讀性——團隊協作時,寫成多行反而更容易比對差異。