CSS background-position-x 属性设置元素背景图像的初始水平位置。图像的位置相对于 background-origin 属性设置的值。
语法
background-position-x: left | center | right | length | percentage | initial| inherit;
属性值
值 | 描述 |
---|---|
left | 将图像设置为左侧位置。 |
center | 将图像设置在水平中心位置。 |
right | 将图像设置到正确的位置。 |
length | 将图像设置为具有给定长度的水平位置。 |
percentage | 根据百分比高度将图像设置在水平位置。 |
initial | 将属性设置为其初始值。 |
inherit | 将继承父元素的属性。 |
CSS 背景位置 X 的示例
下面描述了一些具有不同值的 background-position-x 属性示例。
图像的左侧位置
为了将图像的位置设置为左侧,我们使用左侧值。这在下面的示例中显示。
<!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>
图像的正确位置
为了将图像的位置设置为右侧,我们使用正确的值。这在下面的示例中显示。
<!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>
图像的中心位置
为了将图像的位置设置为居中,我们使用中心值。这在下面的示例中显示。
<!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>
图像与长度的位置
要使用长度定位图像,我们指定值。这在下面的示例中显示。
<!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 方向定位图像,我们还可以使用百分比值。这在下面的示例中显示。
<!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>
支持的浏览器
属性 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
background-position-x | 1.0 | 12.0 | 49.0 | 1.0 | 15.0 |