纯css | 实现流光效果

1,845 阅读2分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

本文主要介绍如何实现按钮的流光效果,使我们的css样式更加的美观,

效果如下:

实现思路

我们使用绝对布局将按钮居中,在使用伪元素+fliter将其实现流光效果,最后使用动画加以背景定位的方法实现最终的效果,也就是我们在封面见到的效果,是不是十分的简单。

实现过程

布局按钮

在这里我们要使用position中的绝对(absolute)使其可以定位在页面的任意地方,使用transform: translate(-50%,-50%);让按钮移动自身宽和高的50%,负号代表着向上和向左移动。最后设置 border-radius: 50px;让按钮形成胶囊状,看起来更加美观。

  display: block;
        position: absolute;
        left: 50%;
         top: 50%;
         transform: translate(-50%,-50%);
        width: 300px;
        height: 100px;
        font-size: 25px;
        text-align: center;//文字居中
        line-height: 100px;
        border-radius: 50px;

实现效果:

屏幕截图 2022-09-24 104335.png

样式修饰

记住一定要使用伪元素,不然实现不了流光的效果,同样也是用绝对定位,将其和按钮重合。再通过background: inherit;继承button的背景效果,最后使用filter: blur(20px);过滤效果做出流光效果。

 button::before{
            content: "";
            position: absolute;
            top: -5px;
            right: -5px;
            bottom: -5px;
            left: -5px;
            width: 300px;
        height: 100px;
        background: inherit;
        filter: blur(20px);
        border-radius: 50px;
        z-index: -1;

动画

先定义动画,是background-position设置背景图片的位置,语法为background-position(x y).在使用动画中的infinite属性使其循环的变化起来 。 animation:动画名称 持续时间 运动曲线 何时开始 播放次数 是否反方向 动画起始或者结束的状态

 @keyframes move{
          100%{
            background-position: 500% 0;
          }
        }
        button:hover{
   animation: move 5s ease infinite;
        }
        button::before:hover{
            animation: move 5s ease infinite;
        } 

结束语

注意一定要写z-index:1;和z-index:-1;不然按钮上的字将会被伪元素覆盖,这个流光效果还有很多挖掘的地方,希望各位小伙伴们尝试一下。