一、CSS 背景屬性概述
CSS 背景屬性用于定義 HTML 元素的背景效果,主要包括以下幾種屬性:
-
background-color
:定義元素的背景顏色。 -
background-image
:定義元素的背景圖像。 -
background-repeat
:定義背景圖像如何重復。 -
background-attachment
:定義背景圖像是否固定或者隨頁面滾動。 -
background-position
:定義背景圖像的起始位置。
二、背景顏色
1. 定義
background-color
屬性用于定義元素的背景顏色。
2. 示例
css復制
body {background-color: #b0c4de;
}
3. 顏色值的表示方法
CSS 中顏色值通常有以下幾種表示方法:
-
十六進制:如
"#ff0000"
。 -
RGB:如
"rgb(255,0,0)"
。 -
顏色名稱:如
"red"
。
4. 應用實例
css復制
h1 {background-color: #6495ed;
}
p {background-color: #e0ffff;
}
div {background-color: #b0c4de;
}
三、背景圖像
1. 定義
background-image
屬性用于定義元素的背景圖像。
2. 默認行為
默認情況下,背景圖像會在水平和垂直方向上平鋪,以覆蓋整個元素。
3. 示例
css復制
body {background-image: url('paper.gif');
}
4. 注意事項
如果背景圖像與文字顏色對比度低,可能會導致文本可讀性差,如下例:
css復制
body {background-image: url('bgdesert.jpg');
}
四、背景圖像的平鋪
1. 水平或垂直平鋪
默認情況下,背景圖像會在水平或垂直方向上平鋪。
2. 示例
css復制
body {background-image: url('gradient2.png');
}
3. 僅水平平鋪
如果希望背景圖像僅在水平方向上平鋪,可以使用 background-repeat: repeat-x;
:
css復制
body {background-image: url('gradient2.png');background-repeat: repeat-x;
}
五、背景圖像的定位與固定
1. 不平鋪
如果不想讓背景圖像平鋪,可以使用 background-repeat: no-repeat;
:
css復制
body {background-image: url('img_tree.png');background-repeat: no-repeat;
}
2. 定位
可以使用 background-position
屬性來改變背景圖像的位置,例如:
css復制
body {background-image: url('img_tree.png');background-repeat: no-repeat;background-position: right top;
}
3. 固定背景圖像
如果希望背景圖像固定,不隨頁面滾動,可以使用 background-attachment: fixed;
:
css復制
body {background-image: url('img_tree.png');background-repeat: no-repeat;background-attachment: fixed;background-position: right top;
}
六、背景簡寫屬性
1. 定義
為了簡化代碼,可以將多個背景屬性合并到一個 background
屬性中。
2. 示例
css復制
body {background: #ffffff url('img_tree.png') no-repeat right top;
}
3. 屬性順序
在使用簡寫屬性時,屬性值的順序為:
-
background-color
-
background-image
-
background-repeat
-
background-attachment
-
background-position
4. 注意事項
-
不需要使用所有屬性,可以根據需要選擇使用。
-
如果省略某些屬性,瀏覽器會使用默認值。
七、CSS 背景屬性總結
屬性 | 描述 |
---|---|
background | 簡寫屬性,將背景屬性設置在一個聲明中。 |
background-attachment | 背景圖像是否固定或者隨頁面滾動。 |
background-color | 設置元素的背景顏色。 |
background-image | 把圖像設置為背景。 |
background-position | 設置背景圖像的起始位置。 |
background-repeat | 設置背景圖像是否及如何重復。 |