linear-gradient()用于创建平滑过渡的背景图像,属于CSS渐变函数,通过background-image设置。1. 基本语法为background-image: linear-gradient(direction, color-stop1, color-stop2, ...);2. direction定义方向如to top或角度;3. color-stop指定颜色及位置,可带百分比精确控制;4. 示例包括从上到下、从左到右、对角线及多色渐变;5. 实际应用需注意使用background-image而非background-color,设置元素高度以确保显示,现代浏览器通常无需厂商前缀,可结合background-size等属性优化效果。掌握方向与颜色停靠点即可灵活运用。

在CSS中使用linear-gradient()可以创建一种平滑过渡的背景色效果。它属于CSS的渐变函数,常用于设置背景图像(background-image),而不是普通的背景颜色(background-color)。
基本语法
linear-gradient()的基本格式如下:
-
direction:渐变的方向,比如
to top、to bottom、45deg等。 - color-stop:颜色值,可带位置(如 20%),也可以不带,均匀分布。
常见用法示例
以下是一些实用的例子帮助理解如何使用:
从上到下的渐变(默认方向)
立即学习“前端免费学习笔记(深入)”;
background-image: linear-gradient(red, blue);从红色平滑过渡到蓝色,方向为从上到下。
从左到右的渐变
background-image: linear-gradient(to right, red, blue);也可写作 90deg:
对角线渐变
background-image: linear-gradient(to bottom right, yellow, green);从左上角向右下角渐变。
多颜色渐变
background-image: linear-gradient(red, yellow, green);三种颜色均匀分布,从上到下依次过渡。
指定颜色位置
background-image: linear-gradient(red 0%, orange 20%, yellow 40%, green 60%, blue 80%, indigo 90%, violet 100%);可以精确控制每种颜色开始的位置,适合制作彩虹条等效果。
实际应用建议
使用渐变时注意以下几点:
- 渐变是
background-image,不是background-color,写错属性会无效。 - 为了兼容老浏览器,有时需要加厂商前缀(现在大多数现代浏览器已不需要)。
- 可以结合
background-size和其它背景属性控制显示效果。 - 如果元素没有内容或高度,可能看不到渐变,记得设置
height或有内容撑开。
基本上就这些,掌握方向和颜色停靠点就能灵活运用 linear-gradient。不复杂但容易忽略细节。










