Style background 屬性

定義和用法

background 屬性以簡寫形式設置或返回最多八個單獨的背景屬性。

通過此屬性,您可以設置/返回以下一項或多項(以任意順序):

DOM 屬性 CSS 屬性
backgroundAttachment background-attachment
backgroundClip background-clip
backgroundColor background-color
backgroundImage background-image
backgroundOrigin background-origin
backgroundPosition background-position
backgroundRepeat background-repeat
backgroundSize background-size

上面的屬性也可以使用單獨的樣式屬性進行設置。強烈建議非高級作者使用單獨的屬性以獲得更好的可控性。

另請參閱:

CSS 教程:CSS 背景

CSS3 教程:CSS3 背景

CSS 參考手冊:background 屬性

實例

設置文檔的背景的樣式:

document.body.style.background = "#f3f3f3 url('img_tree.png') no-repeat right top";

親自試一試

頁面下方有更多 TIY 實例。

語法

返回 background 屬性:

object.style.background

設置 background 屬性:

object.style.background = "color image repeat attachment position size origin clip|initial|inherit"

屬性值

描述
color 設置元素的背景顏色。
image 設置元素的背景圖像。
repeat 設置背景圖像的重復方式。
attachment 設置背景圖像是固定還是隨頁面滾動。
position 設置背景圖像的起始位置。
size 設置背景圖像的大小。
origin 設置背景定位區域。
clip 設置背景圖像的繪制區域。
initial 將此屬性設置為其默認值。請參閱 initial
inherit 從其父元素繼承此屬性。請參閱 inherit

技術細節

默認值: transparent none repeat scroll 0% 0% auto padding-box border-box
返回值: 字符串,表示元素的背景。
CSS 版本: CSS1 + new properties in CSS3

更多實例

例子 2

更改 DIV 元素的背景:

document.getElementById("myDIV").style.background = "url('smiley.gif') blue repeat-x center";

親自試一試

例子 3

為文檔設置背景顏色:

document.body.style.backgroundColor = "red";

親自試一試

例子 4

為文檔設置背景圖像:

document.body.style.backgroundImage = "url('img_tree.png')";

親自試一試

例子 5

將背景圖像設置為不重復:

document.body.style.backgroundRepeat = "repeat-y";

親自試一試

例子 6

將背景圖像設置為固定(不會滾動):

document.body.style.backgroundAttachment = "fixed";

親自試一試

例子 7

更改背景圖像的位置:

document.body.style.backgroundPosition = "top right";

親自試一試

例子 8

返回文檔的背景屬性值:

document.body.style.background;

親自試一試

瀏覽器支持

background 是 CSS1 (1996) 特性。

所有瀏覽器都完全支持它:

Chrome Edge Firefox Safari Opera IE
Chrome Edge Firefox Safari Opera IE
支持 支持 支持 支持 支持 支持

注釋

CSS3 (1999) 中添加了三個新屬性: