17370845950

如何用css background-repeat和background-position调整图片
background-repeat控制背景图重复方式,background-position设置其位置;通过no-repeat、center等值可实现不重复居中显示,常用于美化页面与响应式设计,两者结合简写更高效。

使用 CSS 的 background-repeatbackground-position 可以灵活控制背景图的显示方式和位置。这两个属性常用于美化页面背景、图标布局或响应式设计中。

background-repeat:控制背景图是否重复及重复方向

默认情况下,背景图会水平和垂直方向重复铺满容器。通过 background-repeat 可以改变这一行为。

常用取值:
  • repeat:默认值,图片在水平和垂直方向都重复
  • no-repeat:图片不重复,只显示一次
  • repeat-x:仅在水平方向重复
  • repeat-y:仅在垂直方向重复
  • space:图片不裁剪,等间距排列填满容器
  • round:图片缩放以适应容器,无间隙

例如,防止背景图重复:

css
.element {
  background-image: url('image.jpg');
  background-repeat: no-repeat;
}

background-position:设置背景图的起始位置

这个属性决定背景图在容器中的对齐方式。可以使用关键词、百分比或具体像素值。

常用关键词组合:
  • center center:居中显示(最常用)
  • top left:左上角
  • bottom right:右下角
  • left center:左侧居中垂直

也可以用像素或百分比精确定位:

  • 50% 50%:等同于 center center
  • 20px 10px:距离左边 20px,顶部 10px
  • right 20px bottom 10px:右侧内缩 20px,底部内缩 10px(需配合其他语法)

示例:让背景图居中且不重复:

css
.header {
  background-image: url('logo.png');
  background-repeat: no-repeat;
  background-position: center center;
}

结合使用更灵活

实际开发中,通常将多个 background 相关属性简写为 backgroundbackground-image 的复合写法。

.card {
  background: url('bg.jpg') no-repeat center / cover;
}

上面代码中,no-repeat 控制不重复,center 设置位置,/ cover 是 background-size 的简写,确保图片覆盖整个区域。

基本上就这些。掌握好 repeat 和 position,就能应对大多数背景图布局需求。关键在于根据设计意图选择合适的组合,避免图片变形或错位。