CSS 背景background
CSS 中有5個主要的背景(background)屬性,它們是:
background-color: 指定填充背景的顏色。
background-image: 引用圖片作為背景。
background-position: 指定元素背景圖片的位置。
background-repeat: 決定是否重復(fù)背景圖片。
background-attachment: 決定背景圖是否隨頁面滾動。
這些屬性可以全部合并為一個縮寫屬性: background。需要注意的一個要點是背景占據(jù)元素的所有內(nèi)容區(qū)域,包括 padding 和 border,但是不包括元素的 margin。它在 Firefox, Safari ,Opera 以及 IE8 中工作正常,但是 IE6 和 IE7 中,background 沒把 border 計算在內(nèi)。
背景色(background-color)
background-color 屬性用純色來填充背景。有許多方式指定這個顏色,以下方式都得到相同的結(jié)果。
background-color: blue;
background-color: rgb(0, 0, 255);
background-color: #0000ff;
background-color 也可被設(shè)置為透明(transparent),這會使得其下的元素可見。
背景圖(background-image)
background-image 屬性允許指定一個圖片展示在背景中??梢院?background-color 連用,因此如果圖片不重復(fù)地話,圖片覆蓋不到地地方都會被背景色填充。代碼很簡單,只需要記住,路徑是相對于樣式表的,因此以下的代碼中,圖片和樣式表是 在同一個目錄中的。
background-image: url(image.jpg);
但是如果圖片在一個名為 images 的子目錄中,就應(yīng)該是:
background-image: url(images/image.jpg);
<html> <head> <style type="text/css"> body {background-image: url(這個地方要寫的就是你的圖片的url地址了);} </style> </head> <body> </body> </html>
背景平鋪(background-repeat)
設(shè)置背景圖片時,默認(rèn)把圖片在水平和垂直方向平鋪以鋪滿整個元素。這也許是你需要的,但是有時會希望圖片只出現(xiàn)一次,或者只在一個方向平鋪。以下為可能的設(shè)置值和結(jié)果:
background-repeat: repeat; /* 默認(rèn)值,在水平和垂直方向平鋪 */
background-repeat: no-repeat; /* 不平鋪。圖片只展示一次。 */
background-repeat: repeat-x; /* 水平方向平鋪(沿 x 軸) */
background-repeat: repeat-y; /* 垂直方向平鋪(沿 y 軸) */
background-repeat: inherit; /* 繼承父元素的 background-repeat 屬性*/
<html> <head> <style type="text/css"> body { background-image:url(圖片123.jpg); background-repeat:no-repeat; } </style> </head> <body> </body> </html>
背景的簡寫屬性
可以把背景的各個屬性合為一行,而不用每次都單獨把他們寫出來。格式如下:
background: 《color》 《image》 《position》 《attachment》 《repeat》
例如,下面的聲明
background-color: transparent;
background-image: url(image.jpg);
background-position: 50% 0 ;
background-attachment: scroll;
background-repeat: repeat-y;
可以合為單獨一行:
background: transparent url(image.jpg) 50% 0 scroll repeat-y;
而且不需要指定每一個值。如果省略值地話,就使用屬性地默認(rèn)值。例如,上面那行和下面這個效果一樣:
background: url(image.jpg) 50% 0 repeat-y;
<html> <head> <style type="text/css"> body { background:#ff0000 url(圖片888.jpg) no-repeat fixed center; } </syle> </head> <body> <p>各個屬性間并無順序</p> <p>各個屬性間并無順序</p> <p>各個屬性間并無順序</p> <p>各個屬性間并無順序</p> </body> </html>