纯CSS输出渐变色背景图案 | linear-gradient

992 阅读2分钟

这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战

CSS渐变色逃不过的一个函数就是linear-gradient

MDN官方文档:developer.mozilla.org/zh-CN/docs/…

linear-gradient定义为:

linear-gradient(
  [ <angle> | to <side-or-corner> ,]? <color-stop-list> )
  \---------------------------------/ \----------------------------/
    Definition of the gradient line        List of color stops

where <side-or-corner> = [ left | right ] || [ top | bottom ]
  and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop>
  and <linear-color-stop> = <color> [ <color-stop-length> ]?
  and <color-stop-length> = [ <percentage> | <length> ]{1,2}
  and <color-hint> = [ <percentage> | <length> ]

这个含义看上去很复杂。

比如包括angle渐变方向,是从上到下渐变,还是从左向右渐变,还是以一定角度渐变。

color-stop-list定义的是渐变节点。

我们来看几个例子。

基础框架代码:

<!DOCTYPE html>

<body>
    <div class="my-box"></div>
</body>

<style>
    .my-box {
        width: 300px;
        height: 300px;
        /* background: linear-gradient(#fb3, #58a); */
    }
</style>

</html>
  1. 仅使用颜色:
background: linear-gradient(#fb3, #58a);

效果如下:

image.png

  1. 指定渐变节点

    如下代码所示,我们定义了4个渐变节点,其中第二个与第三个渐变节点的颜色相同。

background: linear-gradient(#fb3 10%, #58a 50%, #58a 60%, red 80%);

展示效果如下所示:

image.png

  1. 指定渐变方向

    我们添加渐变方向,先来尝试一下角度问题:

    background: linear-gradient(45deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
    

    展示效果如下所示,可以看到其中的45deg是左下角开始的。但究竟是从哪里转动的45deg呢?

    image.png

    尝试一下其他的角度,或者我们做一下动画看看:

    <!DOCTYPE html>
    
    <body>
        <div class="my-box"></div>
    </body>
    
    <style>
        .my-box {
            width: 300px;
            height: 300px;
            background: linear-gradient(0deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            animation: change 3s infinite;
        }
        @keyframes change {
            from {
                background: linear-gradient(0deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            }
            25% {
                background: linear-gradient(11.25deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            }
            50% {
                background: linear-gradient(22.5deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            }
            75% {
                background: linear-gradient(33.75deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            }
            to {
                background: linear-gradient(45deg, #fb3 10%, #58a 50%, #58a 60%, red 80%);
            }
        }
    </style>
    
    </html>
    

    动画效果如下:

    499de5d0-e2f0-452d-bc47-96dca17e8b38.gif

    可以看到其转换方向从是“从下到上”的方向开始,大约是以组件中心为圆心顺时针转动45deg

    利用linear-gradient的特性可以做很多有意思的背景色或样式,如条纹等等。《CSS揭秘》中详细阐述了如何使用该属性做条纹以及做更复杂的背景图案。