在CSS样式设置中,背景图片的显示效果往往需要通过多个背景相关属性共同控制,其中background-position和background-repeat是两个核心属性,分别负责调整背景图片的位置和重复行为,理解它们的用法是实现精准背景布局的基础。

background-repeat属性详解
background-repeat属性用于设置背景图片是否在元素内重复显示,以及重复的方向,默认值为repeat,也就是背景图片会在水平和垂直两个方向同时重复,直到铺满整个元素区域。
常用取值说明
- repeat:默认值,背景图片在水平和垂直方向同时重复
- repeat-x:背景图片仅在水平方向重复
- repeat-y:背景图片仅在垂直方向重复
- no-repeat:背景图片不重复,只显示一次
- space:背景图片在重复时,会在图片之间留出均匀的空白,保证图片不会被裁剪,且首尾图片贴紧元素边缘
- round:背景图片在重复时,会根据元素尺寸自动调整图片大小,保证刚好铺满元素区域,没有空白也不会裁剪
代码示例
下面通过不同的取值展示background-repeat的效果:
/* 背景不重复 */
.box1 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: no-repeat;
border: 1px solid #ccc;
}
/* 背景仅水平重复 */
.box2 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: repeat-x;
border: 1px solid #ccc;
}
/* 背景使用space重复 */
.box3 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: space;
border: 1px solid #ccc;
}
background-position属性详解
background-position属性用于设置背景图片在元素内的起始显示位置,当background-repeat设置为no-repeat时,这个属性的效果会非常直观,当背景图片重复时,该属性决定第一张背景图片的起始位置。
常用取值方式
background-position的取值可以是关键词、百分比或者具体的长度单位,取值个数可以是1个或者2个,分别对应水平和垂直方向的位置:
- 关键词取值:水平方向可选left、center、right,垂直方向可选top、center、bottom,如果只写一个关键词,另一个方向默认是center
- 百分比取值:第一个百分比对应水平方向,第二个对应垂直方向,比如50% 50%表示背景图片中心与元素中心对齐
- 长度单位取值:比如px、em等,第一个值对应水平方向距离元素左边缘的偏移,第二个值对应垂直方向距离元素上边缘的偏移,只写一个值时,垂直方向默认是50%
代码示例
下面是不同取值方式的background-position示例:
/* 背景图片放在右上角 */
.box4 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: no-repeat;
background-position: right top;
border: 1px solid #ccc;
}
/* 背景图片水平居中,垂直方向距离顶部20px */
.box5 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: no-repeat;
background-position: center 20px;
border: 1px solid #ccc;
}
/* 背景图片使用百分比定位,中心对齐 */
.box6 {
width: 300px;
height: 200px;
background-image: url('bg.png');
background-repeat: no-repeat;
background-position: 50% 50%;
border: 1px solid #ccc;
}
两个属性的搭配使用
实际开发中,background-position和background-repeat通常会一起使用,来控制背景图片的显示效果,比如实现只显示一次且放在特定位置的背景,或者控制重复背景的起始位置。
下面是一个搭配使用的完整示例,实现一个卡片右上角显示不重复的小图标背景:
.card {
width: 400px;
height: 250px;
padding: 20px;
box-sizing: border-box;
background-image: url('icon.png');
background-repeat: no-repeat; /* 不重复显示背景 */
background-position: right 10px top 10px; /* 距离右边缘10px,上边缘10px */
border: 1px solid #e0e0e0;
border-radius: 8px;
}
如果需要实现背景图片水平重复,且第一张图片从元素左侧50px的位置开始,可以这样设置:
.banner {
width: 100%;
height: 120px;
background-image: url('pattern.png');
background-repeat: repeat-x; /* 水平重复 */
background-position: 50px 0; /* 水平方向偏移50px,垂直方向默认顶部 */
background-color: #f5f5f5;
}
注意事项
- 如果元素没有设置固定的宽高,背景图片的位置和重复效果可能会随着元素尺寸变化而变化,建议给使用背景图片的元素设置明确的尺寸
- 当使用百分比作为background-position的取值时,百分比的计算是基于元素尺寸减去背景图片尺寸后的剩余空间,比如水平方向50%的偏移量是(元素宽度 - 背景图片宽度) * 50%
- background-repeat的space和round取值在部分旧版本浏览器中可能不支持,使用前需要确认兼容性需求
CSSbackground-positionbackground-repeat背景属性修改时间:2026-07-20 04:45:33