CSS通过background或background-image实现渐变,使用linear-gradient创建线性渐变,radial-gradient创建径向渐变,repeating-linear-gradient生成重复条纹,支持多色与透明度,兼容性良好。

CSS 中并没有 background-gradient 这个属性,渐变效果是通过 background 或 background-image 来实现的。你可以使用 CSS 的 linear-gradient()、radial-gradient() 等函数来创建渐变背景。
线性渐变(Linear Gradient)
最常见的渐变类型是从一种颜色平滑过渡到另一种颜色,方向可以是水平、垂直或对角线。
语法:background: linear-gradient(direction, color-stop1, color-stop2, ...);
示例:
立即学习“前端免费学习笔记(深入)”;
从上到下的蓝色渐变:
.box {
background: linear-gradient(blue, lightblue);
}
从左到右的红色到黄色:
.box {
background: linear-gradient(to right, red, yellow);
}
对角线渐变:
.box {
background: linear-gradient(to bottom right, purple, pink);
}
径向渐变(Radial Gradient)
颜色从一个中心点向外扩散,形成圆形或椭圆形渐变。
语法:background: radial-gradient(shape size at position, start-color, ..., last-color);
示例:
立即学习“前端免费学习笔记(深入)”;
.box {
background: radial-gradient(circle, yellow, green);
}
你也可以指定位置:
.box {
background: radial-gradient(at top left, white, black);
}
重复渐变(Repeating Gradient)
如果你想要条纹或重复图案,可以用 repeating-linear-gradient 或 repeating-radial-gradient。
示例:创建彩色条纹背景
.stripes {
background: repeating-linear-gradient(
45deg,
red,
red 10px,
yellow 10px,
yellow 20px
);
}
多色与透明度支持
渐变支持任意数量的颜色节点,还可以结合透明色(如 rgba 或 transparent)做淡出效果。
示例:带透明度的渐变遮罩
.fade-overlay {
background: linear-gradient(
to bottom,
rgba(0,0,0,0),
rgba(0,0,0,0.8)
);
}
基本上就这些。只要用对函数和语法,渐变背景在现代浏览器中兼容性很好,不复杂但容易忽略细节。










