天天看點

background(css複合寫法)

1. 背景-background

==========================================================

單個屬性的寫法

.sample1 {

/*背景顔色*/

background-image: url(sample.gif); /*背景圖檔*/

background-repeat: no-repeat; /*平鋪(?)*/

background-attachment: fixed; /*随文本滾動(?),很少用到*/

background-position: center center; /*背景圖檔位置*/

}

複合屬性的寫法

書寫格式

background : background-color background-image background-repeat background-attachment background-position;

預設值

background: transparent none repeat scroll 0% 0%;

預設值(中文意思)

background: 透明 / 無背景圖檔 / 平鋪 / 背景圖檔随文本滾動(不了解的一定要自己動手試一下) / 位于元素左上角

按照以上的方法,将 .sample1 改成 .sample2,可以得到相同的樣式。

.sample2 {

background: #CCCCCC url(sample.gif) no-repeat fixed center center;

}

background的書寫順序是比較容易了解的。

1. 首先要有背景顔色 background-color ,在背景圖檔(如果有設定)未載入之前,先顯示的是背景顔色。預設為 transparent(透明,即應用父元素或 BODY 的背景設定),可以省略,不過在應用一些JS事件時最好将它寫上,以示規範;

2. 接下來就是背景圖檔 background-image 。如果沒有此項,那麼後面的項就沒有任何意義了;

3. 是否平鋪 background-repeat 要寫在 background-position 之前,很容易了解,如果此項設定了 repeat (鋪滿整個元素),那麼 position 設定就基本失去作用了;

4. fixed 一般用在 body 上,其他地方不大見到;

5. background-position:有2個值,垂直位置和水準位置。按代碼寫法是沒有順序的:比如說背景圖檔位于元素的右下角,可以寫成 bottom right ,也可以寫成 right bottom ;如果按百分比寫法是有順序的:比如 20% 30% ,第1個百分比表示水準位置,第2個百分比表示垂直位置。有意思的是這裡的垂直居中是 center 而不是 middle 。你可以設定一個 center 表示圖檔的居中,相當于 center center 或者 50% 50% 。

==========================================================

2. 字型-font

==========================================================

單個屬性的寫法,這裡隻列出最常用的3個字型屬性。

.sample3 {

font-weight: bold;

font-size: 12px;

font-family: Verdana;

}

複合屬性的寫法

書寫格式(僅css1)

font : font-style font-variant font-weight font-size line-height font-family;

預設值

font: normal normal normal medium normal "Times New Roman" ;

是以上面的.sample3可以寫成這樣

.sample4 {

font: bold 12px Verdana;

}

大家可能會對這個寫法感到陌生,因為font這個複合屬性很少看到,源于它比較嚴苛的書寫要求。

1. font屬性内必須有 font-size 和 font-family 這2項值。如果少了一項,即便将其他字型屬性都寫上也沒用。

如果是這樣 font: bold 12px; 或者 font: bold Verdana; 在絕大部分的浏覽器裡都會表現異常。

2. 書寫順序必須嚴格按照上面提到的順序。

如果寫成 font: 12px bold Verdana; 或者 font: Verdana 12px bold,浏覽器就不會正确解釋。

3. 這裡的12px是表示字型大小,并非行高。

如果要将這兩項同時表現,必須這樣寫:font: bold 12px/2.0em Verdana; ,12px表示字型大小,2.0em(就是12*2.0px)表示行高。

==========================================================

最後要注意的一點:

如果隻有一項值,最好不要應用複合屬性。以免帶來不必要的麻煩。

比如 .sample6 {font-weight: bold} ,如果寫成 .sample6 {font: bold} 就沒任何作用了。

再舉個列子,比如 .sampl5 {background-color: #CCCCCC; } ,如果寫成 .sampl5 {background: #CCCCCC; } ,浏覽器雖然能正确解釋,但這不是規範的寫法。