css | 利用@property实现动态背景渐变色

171 阅读1分钟

前言

我将实现如下所示效果。

动画.gif

@property

首先我们要明白@property可以干嘛。

@property可以用来表示带有值的自定义属性,其可以通过 var() 函数在全文档范围内复用的。形如下例:

@property --property-name {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

syntax代表属性类型,具体可以查阅[MCN](@property - CSS:层叠样式表 | MDN (mozilla.org)),里面有详细的介绍;inherits代表属性是否继承;initial-value代表初始值。

而本文将要实现的动态渐变色就是通过修改自定义角度属性实现的。

代码实现

<template>
  <div class="box">
    <div class="card">记得一键三连哦</div>
    <a href="https://space.bilibili.com/226226311" target="_blank">土拨鼹鼠</a>
  </div>
</template>

<style lang="less" scoped>
a {
  text-decoration: none;
  color: #5ddcff;
}
@property --rotate {
  inherits: false;
  initial-value: 135deg;
  syntax: '<angle>';
}
@keyframes  spin {
  0% {
    --rotate: 0deg;
  }
  100% {
    --rotate: 360deg;
  }
}
.box {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  --card-height: 65vh;
  --card-width: calc(var(--card-height) / 1.5);
  .card {
    height: var(--card-height);
    width: var(--card-width);
    background: #191c29;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #191c29;
    cursor: pointer;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      top: -1%;
      left: -2%;
      width: 104%;
      height: 102%;
      z-index: -1;
      background-image: linear-gradient(
      var(--rotate)
      , #5ddcff, #3c67e3 43%, #4e00c2);
    }
    &::after {
      content: '';
      position: absolute;
      top: calc(var(--card-height) / 6);
      filter: blur(calc(var(--card-height) / 6));
      transform: scale(0.8);
      animation: spin 2.5s linear infinite;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      background-image: linear-gradient(
      var(--rotate)
      , #5ddcff, #3c67e3 43%, #4e00c2);
    }
    &:hover {
      color: rgb(88 199 250 / 360%);
    }
    &:hover {
      &::after, &::before {
        opacity: 0;
      }
    }
  }
}

</style>