linear-gradient() 是图像而非颜色,只能用于 background 或 background-image;方向上 to top 等价于 180deg 而非 0deg;多色需显式标注位置;旧浏览器需手动添加 fallback;渐变受 background-size 等全套背景属性控制。

不能写在 background-color 里,必须用在 background 或 background-image 上——写错位置背景就完全不显示。
为什么 background-color: linear-gradient() 不生效
因为 linear-gradient() 生成的是图像(<image></image> 类型),不是颜色值。CSS 规范里 background-color 只接受颜色(<color></color>),浏览器遇到非法值直接忽略整条声明。
- ✅ 正确:用复合属性
background: linear-gradient(...)(浏览器自动识别为background-image) - ✅ 正确:显式写
background-image: linear-gradient(...) - ❌ 错误:
background-color: linear-gradient(...)(静默失效)
方向参数 to top 和 0deg 完全不是一回事
很多人调角度时发现渐变“转反了”,根源就在这个混淆:CSS 中角度 0deg 默认指向正上方,而 to top 表示“从下往上过渡”,等价于 180deg,不是 0deg。
-
to top=180deg(起点在底部,终点在顶部) -
to bottom=0deg(起点在顶部,终点在底部) -
to right=90deg,to left=270deg - 调试建议:先用
to xxx写法,再在 DevTools 里实时改角度观察变化
多色停靠点不写位置会均分,但多数设计需要精准控制
比如想让黄色占 70% 区域后才切到绿色,就必须显式标注位置;否则浏览器按颜色数量均分,两个颜色就是各 50%,三个就是 0% / 50% / 100%,容易偏离预期。
-
linear-gradient(to right, #f00, #ff0 70%, #0f0)—— 黄色停在 70%,绿色从那里开始过渡 -
linear-gradient(to right, #f00 50%, #00f 50%)—— 硬边切换,适合做分界线 - 避免冗余写
#f00 0%, #00f 100%,除非要覆盖默认分布逻辑 - 单位可用
%、px、rem,但注意响应式场景下是否仍合理
旧浏览器 fallback 必须手动加,别依赖 Autoprefixer
Autoprefixer 已不再为 linear-gradient 加前缀(2026 年起),且 IE10+ 虽支持标准语法,但 IE9 及更早版本完全不识别。仅靠现代写法上线,低版本用户看到的是透明背景。
- 安全写法:先写降级色,再叠渐变,如
background-color: #333; background-image: linear-gradient(...) - 不要用已废弃的
color-stop()语法(如-webkit-gradient(linear, ..., color-stop(...))) - 移动端可忽略 IE,但若项目需兼容 Win7 + IE11,确保没混用实验性特性
真正容易被忽略的是:渐变是图像,所以它受 background-size、background-repeat、background-position 全套背景属性控制——比如做条纹效果,关键不在 linear-gradient 本身,而在 background-size 的尺寸设定和色标硬切配合。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











