女朋友都喜欢的CSS特效:clip-path边框

4,078 阅读3分钟

这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情

大家好,我叫小杜杜,我们知道构成前端的三大语言有:htmlcssjs,其中最为神秘的便是css,为什么这么说呢?自从动画、过度等属性的出现,可以说只有你想不到,就没有做不到~

今天来看看一个特别神奇的属性:clip-path

clip-path

clip-path:裁剪,新的裁剪,与clip相同,只不过clip是老裁剪,并且要absolutefixed定位元素才能使用,并且智能裁剪正方形,这里就不多做赘述,我们直接看clip-path就行

clip-path对元素的定位没有要求,而且也能裁剪更多的元素

用法:clip-path: inset(bottom, right, top, left)

我们来看看裁剪:

image.png

我们发现clip-path的裁剪是挤压,现在来看看clip-path的神奇特效吧

边框线条特效

我们先随便写段文字,添加上背景色,注意,不要对文字限制宽度,可以用padding,这样就能适应文字长度了。像这样

    div{
        background: rebeccapurple;
        line-height: 30px;
        padding: 0 20px;
        color: #fff;
        border-radius: 5px;
    }

image.png

边框

我们现在需要在此处添加一个边框,我们可以利用 after,在通过定位,在通过top等设置边距,如·:

    div{
        position: relative;
        &::after{
            content: "";
            border: 2px solid rebeccapurple;
            position: absolute;
            top: -5px;
            left: -5px;
            right: -5px;
            bottom: -5px;
        }
    }

image.png

clip-path的流动:

经过上面的介绍,我们可以通过 clip-path: inset(bottom, right, top, left)来设定

我们随变写一个值看看效果: clip-path: inset(96% 0 0 0)

image.png

我们要做成动画,假设从上往下,所以应该是初始值为top => right => bottom => left, 在分别设置 25% 50% 75%三个值

像这样:

div{
    &&:after{
        animation: clippath 3s infinite linear;
    }
}

@keyframes clippath {
  0%,
  100% {
      clip-path: inset(0 0 96% 0);
  }
  25% {
      clip-path: inset(0 96% 0 0);
  }
  50% {
      clip-path: inset(96% 0 0 0);
  }
  75% {
      clip-path: inset(0 0 0 96%);
  }
}

img2.gif

双流动特效

除了 after我们还有个before,同时设置延迟时间,防止重合,就OK了,对了,要想让按钮触碰高亮效果可以用filter: contrast()这个属性,参照大佬的,大佬yyds~

img8.gif

变换颜色

我们发现颜色还是太单调了,还是使用老生常谈的颜色filter: hue-rotate(),为了更加好看也可以加入渐变色

img5.gif

图片

当然我们也可以给图片加入边框,效果变成了这样

img9.gif

详细代码

// html
 <div className="Index">
    <div>clip-path: inset 的神奇特效</div>
 </div>

.Index{
  display: flex;
  justify-content: center;
  padding-top: 100px;
  div{
    background: rebeccapurple;
    position: relative;
    line-height: 30px;
    padding: 0 20px;
    color: #fff;
    border-radius: 5px;
    &:hover {
        filter: contrast(1.1);
    }
    
    &:active {
        filter: contrast(0.9);
    }
    &::before,
    &::after{
        content: "";
        border: 2px solid;
        border-image: linear-gradient(45deg, gold, deeppink) 1;
        position: absolute;
        top: -5px;
        left: -5px;
        right: -5px;
        bottom: -5px;
        animation: clippath 3s infinite ;
    }
    &::before{
        animation: clippath 3s infinite -1.5s linear;
    }
  }
}

@keyframes clippath {
  0%,
  100% {
      clip-path: inset(0 0 96% 0);
      filter: hue-rotate(0deg);
  }
  25% {
      clip-path: inset(0 96% 0 0);
  }
  50% {
      clip-path: inset(96% 0 0 0);
      filter: hue-rotate(360deg);
  }
  75% {
      clip-path: inset(0 0 0 96%);
  }
}

END

参考:clip-path 实现边框线条动画 2

不得不说css真的很神奇,最神秘的莫过于css,喜欢的点个赞👍🏻支持下吧(● ̄(エ) ̄●)