no-repeatbackground-repeat 属性的一个值,用于控制背景图片的重复方式,它的核心作用是让背景图片只在指定的位置显示一次,不会在任何方向上平铺重复


no-repeat 的基本用法

no-repeat 通常和 background-imagebackground-position 等属性一起使用,来精确控制背景图片的显示。

语法

selector {
  background-repeat: no-repeat;
}

示例:一个简单的居中背景图

假设我们有一个 div,并希望将一张小图片作为其背景,并且让它居中显示,不重复。

HTML 代码:

<div class="box">
  <p>这是一个带有背景图的盒子。</p>
</div>

CSS 代码:

.box {
  width: 400px;
  height: 250px;
  border: 2px solid #ccc;
  /* 1. 设置背景图片 */
  background-image: url('https://via.placeholder.com/150x100.png?text=Logo');
  /* 2. 设置不重复 */
  background-repeat: no-repeat;
  /* 3. 设置背景图片的位置(居中) */
  background-position: center;
  /* (可选) 为了美观,给背景图一个合适的尺寸 */
  background-size: contain; /* 或者 cover, auto 等 */
}

效果解释:

  • background-image: url(...): 加载你的背景图片。
  • background-repeat: no-repeat: 告诉浏览器,这张图片只显示一次,不会铺满整个盒子。
  • background-position: center: 将这张不重复的图片放置在盒子的中心位置。

background-repeat 的其他常用值

为了更好地理解 no-repeat,我们来看看它的“兄弟们”:

描述 示例图
repeat 默认值,背景图像将在垂直和水平方向上重复。
repeat-x 背景图像将在水平方向上重复,垂直方向不重复。
repeat-y 背景图像将在垂直方向上重复,水平方向不重复。
no-repeat 背景图像将仅显示一次,不重复。
space 背景图像在水平和垂直方向上重复,但图像之间的间距是相等的,并且不会被裁剪。
round 背景图像在水平和垂直方向上重复,但图像会被拉伸或压缩以填满整个区域,不留间隙。

实际应用场景

no-repeat 在网页设计中非常常用,尤其是在以下几种情况:

网站 Logo

将网站的 Logo 放在页面左上角或页面顶部中央,它只需要显示一次。

.header-logo {
  width: 200px;
  height: 60px;
  background-image: url('path/to/your/logo.png');
  background-repeat: no-repeat;
  /* 其他样式... */
}

装饰性图标

在输入框旁边添加一个搜索图标、在链接旁边添加一个外部链接图标等。

.search-input {
  padding-left: 30px; /* 为图标留出空间 */
  background-image: url('path/to/search-icon.png');
  background-repeat: no-repeat;
  background-position: 10px center; /* 图标位置 */
}

大尺寸背景图

使用一张高分辨率的图片作为整个页面的背景,并让它居中显示,不重复。

body {
  background-image: url('path/to/large-background.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed; /* 可选,背景固定不随滚动 */
}

精灵图

no-repeat 是使用 CSS Sprites(精灵图)技术的核心,精灵图将多个小图标合并成一张大图,然后通过 background-position 来精确显示需要的那一部分。

.icon {
  width: 16px;
  height: 16px;
  background-image: url('path/to/sprite.png');
  background-repeat: no-repeat;
}
/* 显示第一个图标 */
.icon-home {
  background-position: 0 0;
}
/* 显示第二个图标 */
.icon-user {
  background-position: -20px 0; /* 向左移动20px */
}

简写属性 background

在实际开发中,我们更常使用 background 这个简写属性来一次性设置所有背景相关的样式,包括 background-repeat

简写语法: background: [background-color] [background-image] [background-repeat] [background-position] / [background-size] [background-origin] [background-clip];

将上面的第一个例子用简写属性重写:

.box {
  width: 400px;
  height: 250px;
  border: 2px solid #ccc;
  /* 使用简写属性 */
  background: url('https://via.placeholder.com/150x100.png?text=Logo') 
              no-repeat 
              center / 
              contain;
  /* 等同于下面这些属性:
  background-image: url(...);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  */
}

no-repeat 是 CSS 中一个基础但极其重要的属性,它让你能够精确控制背景图片的显示方式,避免不必要的重复,是实现 Logo、装饰图标、精灵图和各种精美布局效果的关键,它需要与 background-positionbackground-size 配合使用,以达到最佳的视觉效果。