合理使用縮寫能明顯縮小 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);
border-radius: 10px; /* 四角同值 */ outline: 1px solid #f00; text-decoration: none; transition: all 0.3s ease; animation: slide 1s linear infinite; grid-area: 1 / 2 / 3 / 4; /* 行起 / 列起 / 行止 / 列止 */
縮寫的價值不只是少打字:它讓相關屬性集中在一處,改動時不易遺漏。但要注意,縮寫會重置未寫出的子屬性為默認值——例如 background: url(a.png) 會把 background-position 歸零,覆蓋你此前設定的值。這一點是縮寫引發 bug 的最常見原因。