学习下css的渐变-线性渐变

264 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情

前言

昨天写了一篇用css画一个微笑表情,里面使用到了渐变。今天来讲讲它的用法。

渐变

渐变分为3种,分别是线性渐变,径向渐变,重复渐变。

注意⚠️:渐变用在background-color上无效,要用在background-image或者background。

下面我们先来学习下线性渐变。

线性渐变

语法

background: linear-gradient(direction, color1, color2, ...)

线性渐变默认是从上向下渐变,后面跟着渐变的颜色。

direction为设置渐变的方向,可以是方向值(比如:to right),也可以是角度(单位:deg)。

渐变的起点,和终点是中心对称的。

比如:to right 就是从左往右渐变。 to top就是从下往上渐变。

从左往右渐变

    .box {
      width: 100px;
      height: 100px;
      background-image: linear-gradient(to right, red, blue);
    }

image.png

也可以to 2个方向。to right bottom也就是从左上角向右下角渐变。

    .box {
      width: 100px;
      height: 100px;
      background-image: linear-gradient(to right bottom, red, blue,green);
    }

image.png

下面来看看设置角度的用法

设置角度,是顺时针方向, 整个是360deg。

0deg是top的方向,等同于to top,从下往上渐变。

90deg是top的方向,等同于to right,从左往右渐变。

45deg是右上角,那么就是从左下角往右上角渐变。

    .box {
      width: 100px;
      height: 100px;
      background-image: linear-gradient(45deg, red, blue);
    }

image.png

从下往上渐变,颜色是从红色开始渐变,在20%的时候变成蓝色,最后是绿色。

    .box {
      width: 100px;
      height: 100px;
      background-image: linear-gradient(0deg, red, blue 20%, green);
    }

image.png

background也可以设置多组渐变,通过逗号分隔。

    .box {
      width: 100px;
      height: 100px;
      background-image:
        linear-gradient(90deg, green, transparent 60%),
        linear-gradient(225deg, red, transparent),
        linear-gradient(315deg, blue, transparent);
    }

image.png