這里將會介紹如何通過background-image設置背景圖片,以及背景圖片的平鋪、拉伸、偏移、設置大小等操作。
1. 背景圖片樣式分類
CSS中設置元素背景圖片及其背景圖片樣式的屬性主要以下幾個:
background-image :設置元素的背景圖片。
background-repeat :設置如何平鋪背景圖片。
background-attachment :設置背景圖片是否固定或隨着滾動移動。
background-position :設置背景圖片的位置。
background-size :設置背景圖片的大小。
下面將詳細說明各屬性。
2. background-image :設置元素的背景圖片
說明:可設置元素的1個或多個背景圖片。
語法:<bg-image> [ , <bg-image> ]* | none
默認值:none。 // 不設置元素的背景圖片。
2.1 設置單個背景圖片
說明:默認情況下背景圖片進行橫向和縱向平鋪。
|
1
|
background-image
:
url
(
'res/bgA.jpg'
)
|

2.2 設置多個背景圖片
說明:渲染時前面的背景圖片在上層、后面的背景圖片在下層。
|
1
2
|
background-image
:
url
(
'res/bgA.jpg'
),
url
(
'res/bgB.jpg'
);
background-repeat
:
no-repeat
;
|

3. background-repeat :設置背景圖片的平鋪效果
說明:設置背景圖片的平鋪效果,包括水平、垂直。
語法:<repeat-style> [ , <repeat-style> ]*
<repeat-style> = repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2}
默認值:repeat //水平和垂直平鋪
3.1 background-repeat:repeat-x | repeat-y | repeat-x | repeat-y
說明:設定背景圖片水平、垂直平鋪。
示例:
|
1
2
3
4
5
|
background-repeat
:
repeat-x
;
/* 表示水平平鋪 */
background-repeat
:
repeat-y
;
/* 表示垂直平鋪 */
background-repeat
:
repeat-x
repeat-y
;
/* 水平和垂直平鋪(默認) */
|

3.2 background-repeat:space | round | no-repeat
說明:設置背景圖片的其他平鋪效果。
示例:
|
1
2
3
4
5
|
background-repeat
:space;
/* 均勻的平鋪背景圖片,不會被裁剪 */
background-repeat
:round;
/* 水平和垂直平鋪背景圖片,拉伸圖片以盡可能的填充背景,不會被裁剪 */
background-repeat
:
no-repeat
;
/* 不進行平鋪 */
|

4. background-attachment :設置背景圖片是否固定或隨着滾動移動
說明:設置背景圖片是否固定或隨着滾動移動。
語法:<attachment> [ , <attachment> ]*
<attachment> = scroll | fixed | local
默認值:scroll // 背景圖片跟隨滾動條一直滾動
|
1
2
3
4
5
|
background-attachment
:
scroll
;
/* 跟隨滾動條一起滾動。(默認) */
background-attachment
:
fixed
;
/* 背景圖片固定位置,不隨着滾動條滾動 */
background-attachment
:
local
;
/* 跟隨內容一起滾動 */
|
4.1 background-attachment:scroll; // 跟隨滾動條一直滾動。(默認)

4.2 background-attachment:local; // 跟隨內容一起滾動

5. background-position :設置背景圖片的位置
說明:設置背景圖片的位置,可設置背景圖片的4個邊角水平和縱向的起始位置。
語法:<position> [ , <position> ]*
默認值:0% 0% // 背景圖片左上角定位於容器左上角
5.1 background-position:10px; // 背景圖片水平方向與左邊緣相距10px,垂直居中

5.2 background-position:10px 20px; // 背景圖片水平方向與左邊緣相距0px,垂直方向與頂部邊緣相距20px

5.3 background-position:left 10px bottom 20px; // 背景圖片水平方向與左邊緣相距10px,垂直方向與底部邊緣相距20px

6. background-size :設置背景圖片的大小
說明:設置背景圖片的大小。
<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain
默認值:auto auto // 背景圖片的原始大小
示例:
|
1
2
3
4
5
|
background-
size
:
100px
;
/* 背景圖片寬度為100px,高度為auto */
background-
size
:
100px
50%
;
/* 背景圖片寬度為100px,高度為容器高度的50% */
background-
size
:
100%
100%
;
/* 背景圖片寬度為容器寬度的100%,高度為容器高度的100% */
|

7. 在線示例
地址:http://www.akmsg.com/WebDemo/CSS3-background-image.html
==================================系列文章==========================================
本篇文章:8.2 CSS3 background-image背景圖片相關介紹
