CSS - background-position-x 属性



CSS background-position-x 属性设置元素背景图像的初始水平位置。图像的位置相对于由background-origin 属性设置的值。

语法

background-position-x: left | center | right | length | percentage | initial| inherit;

属性值

描述
left 将图像设置为左侧位置。
center 将图像设置为水平居中位置。
right 将图像设置为右侧位置。
length 使用给定长度将图像设置为水平位置。
percentage 以百分比高度的形式设置图像的水平位置。
initial 这将属性设置为其初始值。
inherit 这从父元素继承属性。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS 背景位置 X 示例

下面描述了一些使用不同值的background-position-x属性示例。

图像的左侧位置

要将图像的位置设置为左侧,我们使用 left 值。这在下面的示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .position-x-left { background-image: url('/css/images/tutimg.png'); background-position-x: left; background-repeat: no-repeat; width: 500px; height: 300px; border: 3px solid black; } </style> </head> <body> <h2>CSS background-position-x property</h2> <div class="position-x-left"></div> </body> </html>

图像的右侧位置

要将图像的位置设置为右侧,我们使用 right 值。这在下面的示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .position-x-left { background-image: url('/css/images/tutimg.png'); background-position-x: right; background-repeat: no-repeat; width: 500px; height: 300px; border: 3px solid black; } </style> </head> <body> <h2>CSS background-position-x property</h2> <div class="position-x-left"></div> </body> </html>

图像的中心位置

要将图像的位置设置为中心,我们使用 center 值。这在下面的示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .position-x-left { background-image: url('/css/images/tutimg.png'); background-position-x: center; background-repeat: no-repeat; width: 500px; height: 300px; border: 3px solid black; } </style> </head> <body> <h2>CSS background-position-x property</h2> <div class="position-x-left"></div> </body> </html>

使用长度定位图像

要使用长度定位图像,我们指定该值。这在下面的示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .position-x-left { background-image: url('/css/images/tutimg.png'); background-position-x: 300px; background-repeat: no-repeat; width: 500px; height: 300px; border: 3px solid black; } </style> </head> <body> <h2>CSS background-position-x property</h2> <div class="position-x-left"></div> </body> </html>

使用百分比定位图像

要沿 X 方向定位图像,我们也可以使用百分比值。这在下面的示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .position-x-left { background-image: url('/css/images/tutimg.png'); background-position-x: 80%; background-repeat: no-repeat; width: 500px; height: 300px; border: 3px solid black; } </style> </head> <body> <h2>CSS background-position-x property</h2> <div class="position-x-left"></div> </body> </html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
background-position-x 1.0 12.0 49.0 1.0 15.0
css_properties_reference.htm
广告