CSS中linear-gradient 的用法
linear-gradient
是 CSS 渐变背景 的一种写法,用于生成沿着直线方向的颜色过渡效果。它常和 background
或 background-image
属性一起使用。
基本语法
background: linear-gradient(direction, color-stop1, color-stop2, ...);
- direction(方向):可以是角度(如
45deg
)、关键字(如to right
,to bottom
等)。 - color-stop(颜色停靠点):颜色值,可以指定位置(百分比或长度),决定渐变分布。
方向写法
-
默认(从上到下)
background: linear-gradient(red, blue);
→ 从上方的红色过渡到底部的蓝色。
-
使用关键字
background: linear-gradient(to right, red, blue);
→ 从左到右渐变。
background: linear-gradient(to bottom right, red, blue);
→ 从左上到右下渐变。
-
使用角度
background: linear-gradient(45deg, red, blue);
→ 沿 45° 方向渐变。
颜色停靠点
你可以通过百分比或长度控制颜色分布:
background: linear-gradient(to right, red 0%, yellow 50%, green 100%);
- 0%:最左侧是红色
- 50%:中间是黄色
- 100%:最右侧是绿色
重复渐变
使用 repeating-linear-gradient
可以创建重复的渐变:
background: repeating-linear-gradient(45deg, red 0, red 10px, blue 10px, blue 20px);
→ 形成条纹效果。
常见应用
-
按钮背景
button {background: linear-gradient(to right, #ff7e5f, #feb47b);border: none;padding: 10px 20px;color: white;border-radius: 8px; }
-
渐变分隔线
hr {border: 0;height: 3px;background: linear-gradient(to right, transparent, #333, transparent); }