CSS background-position-x 属性
定义和用法
background-position-x
属性设置背景图像在 x 轴上的位置。
提示:默认情况下,背景图像放置在元素的左上角,并在垂直和水平方向上重复。
实例
例子 1
如何在 x 轴上定位背景图像:
div { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: center; }
例子 2
如何将背景图像定位到右侧:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: right; }
例子 3
如何使用百分比定位背景图像:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: 50%; }
例子 4
如何使用像素定位背景图像:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: 150px; }
例子 5
使用不同的背景属性创建一个覆盖其容器的背景图像:
.hero-image { background-image: url("photographer.jpg"); /* 使用的图像 */ background-color: #cccccc; /* 如果图像不可用,则使用此颜色 */ height: 300px; /* 必须设置高度 */ background-position-x: center; /* 将图像居中 */ background-repeat: no-repeat; /* 不重复图像 */ background-size: cover; /* 调整背景图像大小以覆盖整个容器 */ }
CSS 语法
background-position-x: value;
属性值
值 | 描述 |
---|---|
left | 将背景定位在 x 轴的左侧。 |
right | 将背景定位在 x 轴的右侧。 |
center | 将背景定位在 x 轴的中心。 |
x% |
x 轴的左侧为 0%,右侧为 100%。 百分比值指的是背景定位区域的宽度减去背景图像的宽度。 |
xpos | 距离左侧的水平距离。单位可以是像素(如 0px)或其他 CSS 单位。 |
xpos offset |
双值语法,仅在 Firefox 和 Safari 中支持。
单位可以是像素或其他 CSS 单位。 |
initial | 将此属性设置为其默认值。参阅 initial。 |
inherit | 从其父元素继承此属性。参阅 inherit。 |
技术细节
默认值: | 0% |
---|---|
继承性: | 否 |
动画制作: | 支持。请参阅:动画相关属性。 |
版本: | CSS3 |
JavaScript 语法: | object.style.backgroundPositionX="center" |
浏览器支持
表格中的数字表示首个完全支持该属性的浏览器版本。
Chrome | Edge | Firefox | Safari | Opera | |
---|---|---|---|---|---|
单值语法 | 1.0 | 12.0 | 49.0 | 1.0 | 15.0 |
双值语法 | 不支持 | 不支持 | 49.0 | 15.4 | 不支持 |
相关页面
教程:CSS 背景
CSS 参考:background-image 属性
CSS 参考:background-position 属性
CSS 参考:background-position-y 属性
HTML DOM 参考:backgroundPosition 属性