背景一行代码就能让页面气质翻倍:从纯色到渐变的最短路径
102
0
0
别把“背景”想成大图堆满屏,它可以是颜色、渐层、小纹理,甚至一张 5KB 的重复图案。
核心就一句:用 CSS,别用 1999 年的 HTML 属性。
1. 老黄历:bgcolor / background 已退休
<!-- 别这么写 -->
<body bgcolor="red" background="bg.jpg">- 不好维护、不能响应式、不能半透明
- 浏览器没报错,但会默默吐槽“这人在考古”
2. 现代三件套:color → image → repeat
/* 1. 先铺底色,图片加载失败也不裸奔 */
body {
background-color: #f5f5f5;
}
/* 2. 再盖图片 */
.hero {
background-image: url("hero.webp");
background-repeat: no-repeat; /* 不拼瓷砖 */
background-position: center; /* 居中 */
background-size: cover; /* 填满容器,允许裁剪 */
}一行简写:
.hero {
background: #f5f5f5 url("hero.webp") no-repeat center / cover;
}3. 不想用图?渐变更快
/* 线性 45° 蓝→紫 */
.gradient {
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
}
/* 径向 蓝→透明→蓝 */
.aura {
background: radial-gradient(circle, rgba(99,102,241,.8) 0%, rgba(99,102,241,0) 70%);
}纯 CSS 生成,零 HTTP 请求,性能满星。
4. 多重背景:一层图+一层色,顺序决定谁在上
.card {
background:
url("logo.svg") right 10px top 10px / 60px auto no-repeat,
linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}先写的在上层,后写的当底色。
5. 实用场景 30 秒复制
① 全屏英雄区
.fullscreen {
min-height: 100vh;
background: url("hero.webp") center/cover no-repeat fixed;
}fixed 让背景不随滚动跑,秒出“视差”效果。
② 文字蒙版
.tint {
position: relative;
background: url("busy-photo.jpg") center/cover;
}
.tint::before {
content: "";
position: absolute;
inset: 0;
background: rgba(0,0,0,.45); /* 半透明黑 */
}
.tint > * { position: relative; z-index: 1; }保证文字可读,对比度 WCAG 直接过。
③ 响应式图片
@media (max-width: 600px) {
.hero { background-image: url("hero-mobile.webp"); }
}移动版用 100KB 小图,桌面版再换 1MB 大图,流量省一半。
6. 最后 3 个提醒
- 图片能压缩就压缩,能 WebP 就 WebP
- 背景再炫也要让文字>4.5:1 对比度,否则好看≠能读
- 别把 5MB 的图设成
background-size: cover还放首屏——用户流量也是钱
记住:背景是配角,先把气氛搞定,再让内容唱戏。
0
快来点个赞吧
发表评论
评论列表