Style backgroundPosition attribute

Definition and Usage

backgroundPosition Set or return the position of the background image within the element.

See also:

HTML Styles:Attribute background

CSS Tutorial:CSS Background

CSS3 Tutorial:CSS3 Background

CSS Reference Manual:Attribute background-image

CSS Reference Manual:Attribute background-position

Sample

Halimbawa 1

Ibinago ang posisyon ng larawan ng background:

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

亲自试一试

Halimbawa 2

Ibinabago ang posisyon ng larawan ng background sa gitna ng ibaba ng <div> element:

document.getElementById("myDiv").style.backgroundPosition = "center bottom";

亲自试一试

例子 3

将 <div> 元素中背景图像的位置更改为水平 200 像素和垂直 40 像素:

document.getElementById("myDiv").style.backgroundPosition = "200px 40px";

亲自试一试

例子 4

返回 <div> 元素中背景图像的位置:

document.getElementById("myDiv").style.backgroundPosition; 

亲自试一试

语法

返回 backgroundPosition 属性:

object.style.backgroundPosition

设置 backgroundPosition 属性:

object.style.backgroundPosition = value

属性值

描述
  • top left
  • top center
  • top right
  • center left
  • center center
  • center right
  • bottom left
  • bottom center
  • bottom right
如果您只规定一个关键字,则另一个值将是 "center"。
x% y%

x 值表示水平位置,y 值表示垂直位置。

左上角是 0% 0%。右下角是 100% 100%。

如果您只规定一个值,则另一个值为 50%。

xpos ypos

x 值表示水平位置,y 值表示垂直位置。

左上角为 0 0。单位可以是像素 (0px 0px) 或任何其他 CSS 单位。

如果您只规定一个值,则另一个值为 50%。您可以混合使用 % 和单位。

initial 将此属性设置为其默认值。请参阅 initial
inherit 从其父元素继承此属性。请参阅 inherit

技术细节

默认值: 0% 0%
返回值: 字符串,表示背景图像的位置。
CSS 版本: CSS1

浏览器支持

backgroundPosition 是 CSS1 (1996) 特性。

所有浏览器都完全支持它:

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