CSS 簡寫,就是把多行屬性壓縮成一行,也稱作 CSS 代碼優化或縮寫。它最大的好處是能顯著縮小 CSS 文件體積、優化網站整體性能,同時讓代碼更易讀。
下面整理了十個常見的 CSS 簡寫規則。
這裡主要指 margin 和 padding 兩個屬性,以 margin 為例,padding 同理。盒子有上下左右四個方向,各有外邊距:
margin-top:1px;
margin-right:2px;
margin-bottom:3px;
margin-left:4px;
可以簡寫為:
margin:1px 2px 3px 4px;
語法為 margin:top right bottom left;
//四個方向相同,等同於 margin:1px 1px 1px 1px;
margin:1px;
//上下為1px、左右為2px,等同於 margin:1px 2px 1px 2px;
margin:1px 2px;
//左右相同,等同於 margin:1px 2px 3px 2px;
margin:1px 2px 3px;
//注意:上下雖都是1px,但這種情況不能縮寫
margin:1px 2px 1px 3px;
邊框的三個屬性:
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 的屬性有:
list-style-type:square;
list-style-position:inside;
list-style-image:url(image.gif);
可縮寫為一句:
list-style:square inside url(image.gif);
16 進制的色彩值,如果每兩位相同,可以縮寫一半。例如:
Aqua: #00ffff —— #0ff
Black: #000000 —— #000
Blue: #0000ff —— #00f
Dark Grey: #666666 —— #666
Fuchsia: #ff00ff —— #f0f
Light Grey: #cccccc —— #ccc
Lime: #00ff00 —— #0f0
Orange: #ff6600 —— #f60
Red: #ff0000 —— #f00
White: #ffffff —— #fff
Yellow: #ffff00 —— #ff0
原則是:如果屬性值為 0,就不必加單位(如 px、em)。你可能會這樣寫:
padding:10px 5px 0px 0px;
試試這樣:
padding:10px 5px 0 0;
最後一條屬性後面的分號可以省略,如:
#nav{
border-top:4px solid #333;
font-style: normal;
font-variant:normal;
font-weight: normal;
}
可簡寫為(去掉最後一個分號):
#nav{
border-top:4px solid #333;
font-style: normal;
font-variant:normal;
font-weight: normal
}
你可能會這樣寫:
h1{
font-weight:bold;
}
p{
font-weight:normal;
}
可以簡寫成:
h1{
font-weight:700;
}
p{
font-weight:400;
}
border-radius 是 CSS3 新增的屬性,用來實現圓角邊框。
-moz-border-radius-bottomleft:6px;
-moz-border-radius-topleft:6px;
-moz-border-radius-topright:6px;
-webkit-border-bottom-left-radius:6px;
-webkit-border-top-left-radius:6px;
-webkit-border-top-right-radius:6px;
border-bottom-left-radius:6px;
border-top-left-radius:6px;
border-top-right-radius:6px;
可以簡寫成:
-moz-border-radius:0 6px 6px;
-webkit-border-radius:0 6px 6px;
border-radius:0 6px 6px;
語法為 border-radius:topleft topright bottomright bottomleft