登录
首页 >  文章 >  前端

CSS背景图技巧:repeat与position使用方法

时间:2026-03-15 11:47:29 344浏览 收藏

掌握CSS中background-repeat与background-position的搭配使用,能精准控制背景图的重复方式与定位效果——无论是让Logo居中不重复、实现无缝平铺、还是响应式适配不同屏幕,只需合理选择no-repeat、repeat-x、center、50% 50%等值,再结合简写语法如background: url(...) no-repeat center / cover,即可高效完成专业级背景布局,大幅提升页面视觉表现力与开发效率。

如何用css background-repeat和background-position调整图片

使用 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,就能应对大多数背景图布局需求。关键在于根据设计意图选择合适的组合,避免图片变形或错位。

理论要掌握,实操不能落!以上关于《CSS背景图技巧:repeat与position使用方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>