CSS 背景屬性用於定義HTML元素的背景。
CSS 屬性定義背影效果:
background-color
background-image
background-repeat
background-attachment
background-position
背景顏色
background-color 屬性定義了元素的背景顏色.
頁面的背景顏色使用在body的選擇器中:
body {background-color:#b0c4de;}
CSS中,顏色值通常以以下方式定義:
十六進制 - 如:”#ff0000”
RGB - 如:”rgb(255,0,0)”
顏色名稱 - 如:”red”
以下實例中, h1, p, 和 div 元素擁有不同的背景顏色:
h1 {background-color:#6495ed;}
p {background-color:#e0ffff;}
div {background-color:#b0c4de;}
背景圖像
background-image 屬性描述了元素的背景圖像.
默認情況下,背景圖像進行平鋪重複顯示,以覆蓋整個元素實體.
頁面背景圖片設置實例:
body {background-image:url('paper.gif');}
背景圖像 - 水平或垂直平鋪
默認情況下 background-image 屬性會在頁面的水平或者垂直方向平鋪。
一些圖像如果在水平方向與垂直方向平鋪,這樣看起來很不協調,如下所示:
body
{
background-image:url('gradient2.png');
}
如果圖像只在水平方向平鋪 (repeat-x), 頁面背景會更好些:
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
背景圖像- 設置定位與不平鋪
讓背景圖像不影響文本的排版
如果你不想讓圖像平鋪,你可以使用 background-repeat 屬性:
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
}
以上實例中,背景圖像與文本顯示在同一個位置,爲了讓頁面排版更加合理,不允許文本的閱讀,我們可以改變圖像的位置。
可以利用 background-position 屬性改變圖像在背景中的位置:
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
}
背景- 簡寫屬性
在以上實例中我們可以看到頁面的背景顏色通過了很多的屬性來控制。
爲了簡化這些屬性的代碼,我們可以將這些屬性合併在同一個屬性中.
背景顏色的簡寫屬性爲 “background”:
body {background:#ffffff url('img_tree.png') no-repeat right top;}
當使用簡寫屬性時,屬性值得順序爲:
background-color
background-image
background-repeat
background-attachment
background-position
以上屬性無需全部使用,你可以按照頁面的實際需要使用.
這個實例使用了先前介紹的CSS,你可以查看相應實例: CSS 實例