渐变
线性渐变
语法:
background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
direction 表示渐变方向,后面表示多个渐变颜色,透明度可使用rgba()
示例:
background-image: linear-gradient(90deg, #f00, #0f0);
使用场景:背景、边框、文本
渐变方向
渐变方向默认从上到下
- 角度值,如
90deg
,度数可为负值,顺时针方向0deg
:从下到上渐变90deg
:从左往右
- 方向值关键词:
to top
:从下到上to right
:从左到右to bottom
:从上到下to left
:从右到左to top right
或to right top
:从左下到右上to top left
或to left top
:从右下到左上to bottom right
或to right bottom
:从左上到右下to bottom left
或to left bottom
:从右上到左下
颜色位置
可以指定颜色停止点的位置,单位可以是百分比、px、em 等
background-image: linear-gradient(red 20%, yellow 50%, green 100%);
在这个例子中,颜色从红色开始,到 20% 处变成黄色,到 50% 处变成绿色,然后从 50% 到 100% 保持绿色
重复渐变
background-image: repeating-linear-gradient(90deg, #f00, #0f0 8%, #00f 20%);
/* 在每隔 20px 的地方重复一次从红色到蓝色的 45 度角度的渐变效果 */
background-image: repeating-linear-gradient(45deg, red, blue 20px);
多重渐变
background-image: linear-gradient(to right, red, blue), linear-gradient(to bottom, green, yellow);
常见效果
示例:变色的文字
/* <div class="box">天下无敌</div> */
.box {
font-weight: 700;
text-fill-color: transparent;
background-image: linear-gradient(left, #007eef, #dc5cb6 25%, #007eef 50%, #dc5cb6 75%, #007eef);
background-size: 200%, 100%;
background-clip: text;
animation: word 3s linear infinite;
}
@keyframes word {
0% {
background-position: 0 0;
}
100% {
background-position: -100% 0;
}
}