該性質是用於定義一個元素的背景效果。
Background-color
該性質用來指定一個元素的背景顏色。
注意: The background of an element is the total size of the element, including padding and border (but not the margin).
一個元素的背景指的是除了外邊距之外元素完整的大小,包含內邊距和邊框。
Background-image
該性質用於給一個元素指定一張圖片作爲背景。
body
{
background-image: url("img_tree.gif");
}
不要背景圖:background-image: none;
Tip: Always set a background-color to be used if the image is unavailable.
以防背景圖片不可用,記住要設置背景顏色。
Background-repeat
By default, a background-image is placed at the top-left corner of an element, andrepeated both vertically and horizontally,
默認情況下,背景圖片被放置在一個元素的左上角,同時沿水平方向和垂直方向重複擺放。
有時爲了更好的效果,只需要 repeat-x 水平重複或者 repeat-y 垂直重複。
如:實現從上到下顏色的漸變效果
body
{
background-image:url("gradient2.png");
background-repeat:repeat-x;
}
不需要重複時,設置性質的值爲 no-repeat.
Background-position
使用該性質來定位背景圖片的位置。
body
{
background-image:url("img_tree.png");
background-repeat:no-repeat;
background-position:right top;
}
可取的值:
left top left center left bottom right top right center right bottom center top center center center bottom |
If you only specify one keyword, the other value will be "center" 如果只寫一個關鍵詞,另一個值將爲“居中” |
x% y% | The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50% . Default value is: 0% 0% |
xpos ypos | The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions |
Background-attachment
該性質指定了一張背景圖片是否位置固定,還是與頁面剩餘部分一起滾動。
取值:
- scroll:scrolls along with the element. This is default, 背景圖像隨頁面其餘部分一起滾動
- fixed:fixed with regard to the viewport,
- local:scrolls along with the element's contents, 和元素內容一起滾動。
Background-size
background-size: auto|length|cover|contain|initial|inherit;
1. coverthe background image will scale to cover the entire content area. Notice that the "cover" value keeps the aspect ratio, and some part of the background image may be clipped
背景圖將放大以完全覆蓋住內容區域。注意:背景圖的 width 達到其所在元素寬度的100%,保持寬高比,等比放大,圖片部分位置可能因此 invisible。
2. 100% 100%
圖片的寬和高會拉伸以完全覆蓋住內容區域,非等比放大。
3. contain
the background image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship between the image's width and height)
背景圖會放大,盡力去填滿內容區域(通常填不滿),但是保持寬高比,等比放大,寬和高分別頂住所在元素的邊緣。
Background-clip & Background-origin
- background-clip: border-box|padding-box|content-box|initial|inherit;
- background-origin: padding-box|border-box|content-box|initial|inherit;
簡寫Background性質
從上面的幾個例子可以看到,許多性質都是在處理背景。爲了簡化代碼,可以把一些性質寫進一個單獨的性質裏。
The shorthand property for background is simply "background"
簡寫順序需遵循如下規則:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
以上性質如果有一個或幾個缺省,沒關係,只有遵循這個順序寫就行。