背景
渐变与 attachment。
背景
这一课你将能做到
- 控制背景色、背景图、位置、大小、重复、附着方式
- 用 background 简写属性写紧凑代码
- 写出常见的视觉效果:封面图、水印、纹理、多层背景
为什么要学
背景是页面的「底色和质感」。一个空白背景的网站像没装修的房子;加了渐变、纹理、封面图,立刻有了氛围。hero 大图、卡片缩略图、文章封面……全靠 background 系列属性。
人话:背景属性就像给墙贴壁纸——选什么颜色(color)、贴什么图(image)、贴多大(size)、从哪开始贴(position)、贴不贴满(repeat)、跟着人走还是钉死(attachment)。
先建立图像
<style>
.demo {
width: 400px;
height: 200px;
border: 1px solid #ddd;
margin-bottom: 12px;
color: #fff;
padding: 12px;
}
.d1 { background-color: #2c3e50; }
.d2 {
background-image: linear-gradient(135deg, #667eea, #764ba2);
}
.d3 {
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><circle cx="10" cy="10" r="2" fill="%23fff"/></svg>');
background-repeat: repeat;
background-color: #333;
}
</style>
<div class="demo d1">纯色背景</div>
<div class="demo d2">渐变背景</div>
<div class="demo d3">重复纹理背景</div>
跟着做
步骤 1:background-color 背景色
.box { background-color: #f5f5f5; }
.box { background-color: rgba(0, 0, 0, 0.5); } /* 半透明 */
.box { background-color: transparent; } /* 透明(默认) */
背景色会铺满 content + padding + border 区域(除非用 background-clip 改变)。
步骤 2:background-image 背景图
.box { background-image: url("hero.jpg"); }
.box { background-image: linear-gradient(to right, red, blue); } /* 渐变也是 image */
.box {
background-image:
url("logo.png"),
linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.3)),
url("bg.jpg");
/* 多层背景,前面的在上面 */
}
步骤 3:background-repeat 平铺方式
.box { background-repeat: repeat; } /* 默认,双向平铺 */
.box { background-repeat: no-repeat; } /* 不平铺 */
.box { background-repeat: repeat-x; } /* 横向平铺 */
.box { background-repeat: repeat-y; } /* 纵向平铺 */
.box { background-repeat: space; } /* 平铺但保持完整图 */
.box { background-repeat: round; } /* 平铺且拉伸凑整 */
步骤 4:background-position 位置
.box { background-position: center; } /* 居中 */
.box { background-position: top right; } /* 关键字组合 */
.box { background-position: 50% 50%; } /* 百分比 */
.box { background-position: 20px 30px; } /* 像素:x y */
.box { background-position: right 10px bottom 20px; } /* 距右 10 距底 20 */