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 ɗanɗin

CSS3 教程:CSS3 背景

CSS 参考手册:background 属性

实例

设置文档的背景的样式:

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

Try it yourself

页面下方有更多 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 Dabbuɗa ita taɓbasuwar a kiyawar da ta gina. Ci gaba da initial.
inherit Yi taɓbasuwar wasan ita daga iyana abinɗin. Ci gaba da inherit.

sabon fari

Kiyawar: transparent none repeat scroll 0% 0% auto padding-box border-box
Kiyawar: kalamar, wanda ke fice taɓbasuwar jiki.
ṣanannun CSS: CSS1 + matsayiyyar new fi CSS3

ḍarurarun

ḍari 2

ṣaṣa taɓbasuwar DIV

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

Try it yourself

Example 3

Set the background color for the document:

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

Try it yourself

Example 4

Set the background image for the document:

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

Try it yourself

Example 5

Set the background image to non-repeating:

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

Try it yourself

Example 6

Set the background image to fixed (it will not scroll):

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

Try it yourself

Example 7

Change the position of the background image:

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

Try it yourself

Example 8

Return the background attribute value of the document:

document.body.style.background;

Try it yourself

Browser support

background Is a feature of CSS1 (1996).

All browsers fully support it:

Chrome Edge Firefox Safari Opera IE
Chrome Edge Firefox Safari Opera IE
Support Support Support Support Support Support

Comments

Three new attributes were added in CSS3 (1999):