简介
linear-gradient()
函数在 CSS 中用于创建线性渐变效果。它可以创建从一种颜色平滑过渡到另一种颜色的效果,并可以指定渐变的方向和颜色停止点。
语法
linear-gradient(direction, color-stop1, color-stop2, ...);
其中:
- direction:指定渐变的方向,可以是以下值之一:
to top
to bottom
to left
to right
to top left
to top right
to bottom left
to bottom right
- color-stop:指定渐变中的颜色停止点。每个颜色停止点由以下部分组成:
- 颜色值(十六进制、RGB、RGBA、HSL、HSLA)
- 可选的百分比值,指定颜色停止点的位置(从 0% 到 100%)
示例
创建一个从蓝色到红色的水平渐变:
background: linear-gradient(to right, blue, red);
创建一个从左上角到右下角的对角线渐变:
background: linear-gradient(to bottom right, blue, red);
创建具有多个颜色停止点的渐变:
background: linear-gradient(to bottom, blue 0%, green 50%, red 100%);
角度渐变
除了使用方向关键字外,还可以使用角度值来指定渐变方向。角度以顺时针方向从水平轴(0 度)测量。
background: linear-gradient(45deg, blue, red);
重复渐变
默认情况下,渐变仅在元素的边界内重复一次。可以使用 repeat
关键字使渐变重复多次。
background: repeating-linear-gradient(to right, blue, red);
附加选项
linear-gradient()
函数还支持以下附加选项:
- color-hint:指定浏览器如何渲染渐变,可以是以下值之一:
optimizeSpeed
:优化渲染速度optimizeQuality
:优化渲染质量no-hint
:不指定渲染优先级
- fallback-color:指定当浏览器不支持
linear-gradient()
函数时的回退颜色
浏览器支持
linear-gradient()
函数在所有现代浏览器中都得到广泛支持,包括 Chrome、Firefox、Safari、Edge 和 Opera。
兼容性问题
在 Internet Explorer 9 及更早版本中,linear-gradient()
函数不受支持。可以使用 CSS3 Pie 或其他兼容性库来解决此问题。