CSS 背景位置

背景位置是CSS中用于控制背景图片在元素内位置的属性,它可以精确地定位背景图片的显示位置。

基本语法

css
元素选择器 {
  background-position: 水平位置 垂直位置;
}

位置值的表示方法

background-position属性支持多种位置值的表示方法:

1. 关键字

使用预定义的关键字表示位置:

  • 水平方向:left(左)、center(中)、right(右)
  • 垂直方向:top(上)、center(中)、bottom(下)
css
.element {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: left top; /* 左上角 */
}

可以只指定一个关键字,另一个方向默认为center

css
.element {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: center; /* 水平居中,垂直居中 */
}

.element2 {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: left; /* 左对齐,垂直居中 */
}

2. 长度值

使用像素(px)、厘米(cm)等长度单位表示位置,相对于元素的左上角:

css
.element {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: 50px 20px; /* 距离左边缘50px,距离上边缘20px */
}

3. 百分比值

使用百分比表示位置,相对于元素和背景图片的尺寸:

css
.element {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: 50% 50%; /* 居中显示 */
}

百分比值的计算方式:

  • 水平位置:元素宽度 × 百分比 - 图片宽度 × 百分比
  • 垂直位置:元素高度 × 百分比 - 图片高度 × 百分比

这意味着50% 50%总是使背景图片居中显示,无论元素和图片的尺寸如何。

4. 混合使用

可以混合使用不同类型的位置值:

css
.element {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: 20px center; /* 距离左边缘20px,垂直居中 */
}

.element2 {
  background-image: url('images/logo.png');
  background-repeat: no-repeat;
  background-position: center 50px; /* 水平居中,距离上边缘50px */
}

多背景图片的位置

对于多个背景图片,可以使用逗号分隔的位置值列表:

css
.element {
  background-image: 
    url('images/image1.png'),
    url('images/image2.png'),
    url('images/image3.png');
  background-repeat: 
    no-repeat,
    no-repeat,
    no-repeat;
  background-position: 
    left top,
    center center,
    right bottom;
}

应用场景

1. 居中显示背景图片

css
.hero {
  background-image: url('images/hero-bg.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: 500px;
}

2. 定位装饰性元素

css
.box {
  background-image: url('images/ribbon.png');
  background-repeat: no-repeat;
  background-position: right top;
  padding: 20px;
  position: relative;
}

3. 创建图标系统

css
.icon {
  width: 24px;
  height: 24px;
  background-image: url('images/icons.png');
  background-repeat: no-repeat;
  display: inline-block;
}

.icon-home {
  background-position: 0 0;
}

.icon-search {
  background-position: -24px 0;
}

.icon-settings {
  background-position: 0 -24px;
}

4. 响应式背景图片

css
.responsive-bg {
  background-image: url('images/bg.jpg');
  background-repeat: no-repeat;
  background-position: 10% center;
  background-size: contain;
  padding: 40px;
}

浏览器兼容性

浏览器 支持情况
Chrome 完全支持
Firefox 完全支持
Safari 完全支持
Edge 完全支持
IE IE6及以上支持

多背景图片的位置在IE9及以下浏览器中不支持。

总结

background-position是CSS中用于控制背景图片位置的重要属性,它支持多种位置值的表示方法和灵活的使用方式。合理使用background-position可以精确地定位背景图片,实现各种复杂的视觉效果。

最后更新:2026-02-07