一、background-position 概述
CSS background-position
可以用来设置页面元素(如:div、img 等)背景图像(background-image
)的位置,其基本语法如下:
background-position: [left|center|right] [top|center|bottom];
其中,left|center|right
用于设置水平方向位置,top|center|bottom
用于设置垂直方向位置。
如果只设置一个值,则该值为水平方向位置,垂直方向的位置默认为 center
。
使用 background-position
指定背景位置时,水平方向的值决定了背景图像在背景容器内水平位置的起点,垂直方向的值决定了背景图像在背景容器内垂直位置的起点。
二、background-position 单位
CSS background-position
的位置单位可以使用绝对单位(如:px、em 等)或相对单位(如:百分比%)。
当使用百分比时,水平方向的值为背景图像的水平宽度在容器内的位置,垂直方向的值为背景图像的垂直高度在容器内的位置。
三、background-position 关键字
CSS background-position
支持三个关键字:left
、center
、right
、top
、bottom
。
当省略某个位置时,默认值为 center
。可以通过使用两个关键字组合,指定背景图像在水平和垂直方向的位置。
background-position: left top;
background-position: right bottom;
background-position: center center;
四、background-position 多背景图像
CSS3 中,background-position
还可以用于设置多背景图的位置。当使用多背景图时,需要指定每一个背景图的位置,依次为:
- 图片URL
- 定位信息
- 是否重复
每个图片的定位信息都由两个数值表示,用逗号分隔,分别用于设置水平方向和垂直方向的位置,如:
.container {
background-image: url(image1.png), url(image2.png);
background-position: 10px 10px, 20px 20px;
background-repeat: no-repeat;
}
五、background-position 使用技巧
使用 background-position
可以轻松实现以下效果:
- 图像水平居中或垂直居中
- 图像位置微调,使元素更加美观
- 定位多背景图像
六、示例代码
.container {
background-image: url('background.png');
background-position: center center;
background-repeat: no-repeat;
}
以上代码将容器的背景图像设置为 background.png
,并将其位置设置为居中。
.container {
background-image: url('background.png');
background-position: 20px 10px;
background-repeat: no-repeat;
}
以上代码将容器的背景图像设置为 background.png
,并将其位置微调为距离容器左侧 20px
,距离容器顶部 10px
。
.container {
background-image: url('background1.png'), url('background2.png');
background-position: left top, right bottom;
background-repeat: no-repeat;
}
以上代码设置了两个背景图像:background1.png
和 background2.png
,一个定位在页面左上角,另一个定位在页面右下角。