linear-gradient用于创建线性渐变背景,语法为background-image: linear-gradient(direction, color-stop1, color-stop2, ...),支持方向关键词或角度,可自定义颜色停靠点实现多色过渡,常用于按钮、卡片等视觉增强场景。

在CSS中,linear-gradient 是一种创建线性渐变背景的方法,可以让你用纯代码实现平滑的颜色过渡,无需图片。它属于 background-image 属性的值之一,使用灵活且兼容性良好。
基本语法
linear-gradient 的基本语法如下:
background-image: linear-gradient(direction, color-stop1, color-stop2, ...);- direction:渐变方向,可以是角度(如 45deg)或关键词(如 to bottom、to right)
- color-stop:颜色值,可带位置(如 red 0%、blue 100%)
常见方向写法
你可以通过关键词或角度控制渐变方向:
- to bottom:从上到下(默认)
- to top:从下到上
- to right:从左到右
- to left:从右到左
- to bottom right:从左上到右下
- 45deg:按角度,0deg 是向上,90deg 是向右
示例:从红色到蓝色的垂直渐变
立即学习“前端免费学习笔记(深入)”;
background-image: linear-gradient(to bottom, red, blue);自定义颜色停靠点
你可以在特定位置指定颜色,实现更精细的控制:
background-image: linear-gradient(to right, red 0%, yellow 50%, green 100%);- red 从 0% 开始
- yellow 在 50% 位置
- green 到达 100%
这种写法适合制作多色条纹或模拟仪表进度条效果。
实际应用建议
- 推荐使用 background-image 而不是旧的 background 简写,避免覆盖其他背景设置
- 为兼容老浏览器,可添加 -webkit- 前缀(现代项目通常不需要)
- 渐变不支持 opacity 过渡?可以用 rgba 颜色实现透明效果,例如 rgba(255,0,0,0.5)
- 可以用在按钮、卡片、背景图层、分隔区域等视觉增强场景
基本上就这些。掌握 linear-gradient 能让你的页面色彩更生动,同时减少资源请求。不复杂但容易忽略细节,比如方向和颜色分布。多试几次就能熟练了。










