CSS 背景

CSS 提供了丰富的背景样式控制,从纯色到图片、从渐变到蒙版。

background-color — 背景色

最基础的背景属性:

css
body {
  background-color: #f8fafc;
}

.card {
  background-color: white;
}

background-image — 背景图

使用 url() 引入图片:

css
.hero {
  background-image: url('hero-bg.jpg');
}

background-repeat — 重复方式

默认情况下背景图会在水平和垂直方向重复平铺:

css
.banner {
  background-image: url('pattern.png');
  background-repeat: repeat;    /* 平铺(默认) */
  background-repeat: repeat-x;  /* 仅水平平铺 */
  background-repeat: repeat-y;  /* 仅垂直平铺 */
  background-repeat: no-repeat; /* 不平铺 */
}

background-size — 背景尺寸

说明
cover等比例缩放,覆盖整个容器(可能裁剪)
contain等比例缩放,完整显示图片(可能留白)
100px 200px固定宽高
50% auto百分比
css
.hero {
  background-image: url('hero.jpg');
  background-size: cover;
  min-height: 400px;
}

background-position — 背景位置

指定背景图的起始位置:

css
.banner {
  background-image: url('banner.jpg');
  background-repeat: no-repeat;
  background-position: center;         /* 居中 */
  background-position: top right;      /* 右上角 */
  background-position: 10px 20px;      /* 距左 10px,距上 20px */
  background-position: 50% 50%;        /* 百分比居中 */
}

background-attachment — 滚动行为

控制背景图是否随页面滚动:

css
.hero {
  background-attachment: scroll; /* 随元素滚动(默认) */
  background-attachment: fixed;  /* 固定在视口,不随滚动 */
  background-attachment: local;  /* 随元素内容滚动 */
}

fixed 可以创建视差效果:背景图不动,内容在上面滚动。

background 简写

所有背景属性可以合并到一条 background 中:

css
.hero {
  background: url('hero.jpg') no-repeat center / cover #1e293b;
  /*          background-image    repeat   position / size  color */
}

简写中 background-size 必须紧跟在 background-position 后面,用 / 分隔。顺序可以灵活,但 positionsize 前面。

渐变背景(Gradient)

渐变用 linear-gradient()radial-gradient() 生成,不需要图片:

线性渐变

css
/* 从上到下(默认方向) */
.gradient {
  background: linear-gradient(#2563eb, #7c3aed);
}

/* 从左到右 */
.gradient-h {
  background: linear-gradient(to right, #2563eb, #7c3aed);
}

/* 指定角度 */
.gradient-angle {
  background: linear-gradient(45deg, #2563eb, #7c3aed);
}

/* 多色渐变 */
.gradient-multi {
  background: linear-gradient(to right, #ef4444, #f97316, #eab308, #22c55e, #2563eb);
}

/* 色标控制位置 */
.gradient-stops {
  background: linear-gradient(to right, #2563eb 0%, #2563eb 30%, #7c3aed 100%);
  /* 前 30% 是纯蓝,30%~100% 渐变到紫 */
}

径向渐变

从中心向外辐射:

css
.circle {
  background: radial-gradient(circle, #2563eb, #1e3a5f);
}

.spotlight {
  background: radial-gradient(circle at 20% 30%, white, #1e293b);
}

多重背景

一个元素可以叠加多个背景,用逗号分隔:

css
.layered {
  background:
    url('overlay.png') repeat,
    linear-gradient(135deg, #2563eb, #7c3aed),
    #1e293b;
  /* 越靠前越在上层 */
}