CSS background-position
属性用于设置背景图片的位置。例如,
div {
background-image: url("avatar.png");
background-repeat: no-repeat;
background-position: center;
}
浏览器输出

在上面的示例中,我们使用 background-position
属性将背景图片居中。
CSS background-position 语法
background-position
属性的语法是:
background-position: length value(s) | percentage value(s) | keyword(s) | initial | inherit;
这里,
length values
:使用长度单位(如px
、em
等)定位背景图片percentage values
:使用百分比定位背景图片keywords
:使用top
、bottom
、left
、right
和center
关键字定位背景图片initial
:将属性值设置为默认值inherit
:继承其父元素的属性值。
示例 1:使用长度单位
让我们看一个使用长度单位 px
的 background-position
属性的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-position</title>
</head>
<body>
<!-- Adding background image -->
</body>
</html>
body {
height: 100vh;
background-image: url("https://programiz.com.cn/blog/content/images/2022/03/Banner-Image-1.png");
background-repeat: no-repeat;
/* positions image 100px from the left and vertically center by default*/
background-position: 100px;
}
浏览器输出

在上面的例子中:
background-position: 100px;
将背景图片定位在距离 left
100px
的位置,并在垂直方向上默认居中对齐。
我们还可以提供一个可选的第二个值来为背景图片提供垂直位置。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-position</title>
</head>
<body>
<!-- Adding background image -->
</body>
</html>
body {
background-image: url("https://programiz.com.cn/blog/content/images/2022/03/Banner-Image-1.png");
background-repeat: no-repeat;
/* positions image to 100px from left and 50px from the top */
background-position: 100px 50px;
}
浏览器输出

示例 2:使用百分比
让我们看一个使用百分比的 background-position
属性的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-position</title>
</head>
<body>
<div class="container"><!-- Adding background image --></div>
</body>
</html>
body {
height: 100vh;
background-image: url("https://programiz.com.cn/blog/content/images/2022/03/Banner-Image-1.png");
background-repeat: no-repeat;
/* positions image to 10% from the left and 50% from the top */
background-position: 10% 50%;
}
浏览器输出

示例 3:使用关键字
让我们看一个使用关键字的 background-position
属性的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-position</title>
</head>
<body>
<div class="container"><!-- Adding background image --></div>
</body>
</html>
body {
background-image: url("https://programiz.com.cn/blog/content/images/2022/03/Banner-Image-1.png");
background-repeat: no-repeat;
/* positions image top right */
background-position: top right;
}
浏览器输出
