css制作渐变
CSS 渐变基础
CSS 渐变允许在元素背景中创建平滑的颜色过渡效果,无需使用图像。主要分为线性渐变(linear-gradient)和径向渐变(radial-gradient)。
线性渐变(Linear Gradient)
线性渐变沿一条直线方向过渡颜色。语法如下:
background: linear-gradient(direction, color-stop1, color-stop2, ...);
方向参数:
- 使用角度(如
45deg)或关键词(如to right、to bottom left)。 - 默认方向为从上到下(
to bottom)。
示例:
/* 从左到右的红色到蓝色渐变 */
background: linear-gradient(to right, red, blue);
/* 45度角的黄色到绿色渐变 */
background: linear-gradient(45deg, yellow, green);
/* 多色渐变 */
background: linear-gradient(to bottom, red, orange, yellow);
径向渐变(Radial Gradient)
径向渐变从中心点向外扩散颜色。语法如下:
background: radial-gradient(shape size at position, color-stop1, color-stop2, ...);
参数说明:

shape:可选circle或ellipse(默认)。size:定义渐变范围(如farthest-corner、closest-side)。position:中心点位置(如at center、at top left)。
示例:
/* 圆形渐变,从中心向外 */
background: radial-gradient(circle, red, blue);
/* 椭圆形渐变,自定义位置 */
background: radial-gradient(ellipse at top right, yellow, green);
重复渐变
通过 repeating-linear-gradient 或 repeating-radial-gradient 实现重复渐变效果。
示例:
/* 重复的条纹渐变 */
background: repeating-linear-gradient(45deg, red, red 10px, blue 10px, blue 20px);
/* 重复的径向渐变 */
background: repeating-radial-gradient(circle, yellow, yellow 10%, green 10%, green 20%);
渐变实用技巧
透明度支持
使用 rgba() 或 hsla() 实现透明渐变:

background: linear-gradient(to right, rgba(255,0,0,0.5), rgba(0,0,255,0.8));
硬色标(Hard Color Stops)
通过相同位置的颜色节点创建锐利过渡:
background: linear-gradient(to right, red 50%, blue 50%);
浏览器兼容性
添加前缀确保兼容旧版浏览器:
background: -webkit-linear-gradient(left, red, blue);
background: -moz-linear-gradient(left, red, blue);
background: linear-gradient(to right, red, blue);
实际应用场景
按钮悬停效果
.button {
background: linear-gradient(to bottom, #4CAF50, #45a049);
}
.button:hover {
background: linear-gradient(to bottom, #45a049, #4CAF50);
}
背景纹理
.background {
background: repeating-linear-gradient(
-45deg,
#f0f0f0,
#f0f0f0 10px,
#e0e0e0 10px,
#e0e0e0 20px
);
}






