CSS渐变色边框新方案

583 阅读2分钟

使用 background-clip: border-area; 来绘制渐变色边框,如下图所示:

image.png

我们通常使用 background-image 来绘制一个渐变色的边框,达到上述效果通常需要复杂的代码:

<template>
  <div class="text-wrapper">
      <div class="text">
         <div class="text-inner">
          Let's Go
        </div>
      </div>
  </div>
</template>

<style scoped lang="scss">
.text-wrapper {
  position: relative;
  display: flex;
  width: 180px;
  height: 43px;
  padding: 2px;
  border-radius: 50px;
  background-image: linear-gradient(91deg, #e5000e 0%, #fc9f09 100%);
  background-origin: border-box;
  background-clip: border-box;

  .text {
    display: flex;
    flex: 1;
    justify-content: center;
    align-items: center;
    border-radius: 50px;
    background-color: #fff;

    .text-inner {
      font-weight: 700;
      color: transparent;
      background-image: linear-gradient(91deg, #e5000e 0%, #fc9f09 100%);
      -webkit-background-clip: text; /* stylelint-disable-line */
    }
  }
}
</style>

但是现在有了background-clip: border-area;,我们可以简单地直接填充边框了。

Safari 技术预览版和 Safari 18.2 betabackground-clip: border-area现已提供支持。`

边框和文本都需要实现渐变,为了实现这一点,我们使用两个 linear-gradient作为背景图像,并将 background-clip 设置为 border-area, text:

.text-wrapper
  color: transparent;
  border: 10px solid transparent;
  border-radius: 100px;
  background-image:  linear-gradient(91deg, #e5000e 0%, #fc9f09 100%), 
                     linear-gradient(91deg, #e5000e 0%, #fc9f09 100%);
  background-origin: border-box;
  background-clip:   border-area, 
                     text;
}

目前,background-clip: border-area; 这个属性的浏览器兼容性有限,尚未被广泛支持。然而,随着浏览器的不断更新和 CSS 标准的演进,我们可以期待在不久的将来它会被更多的浏览器所支持。

image.png

为了确保你的项目在所有环境中都能正常运行,建议在使用该属性时提供适当的回退方案。最简单的方法就是为同一属性提供多个值。例如:

background-clip: text;
background-clip: border-area;

在 css 中,声明从上到下进行评估,后面的值会覆盖前面的值。也就是说,在支持的浏览器中,background-clip: text; 将被 background-clip: border-area, text; 覆盖;在不支持的浏览器中,background-clip: border-area, text; 不会被识别为有效值,并将被忽略,因此background-clip: text; 生效。

当我们希望使用一组替代样式时,可以使用 @support 规则:

@supports (background-clip: border-area) {
  .text-wrapper {
    color: transparent;
    border: 2px solid transparent;
    border-radius: 50px;
    background-image:
      linear-gradient(91deg, #e5000e 0%, #fc9f09 100%),
      linear-gradient(91deg, #e5000e 0%, #fc9f09 100%);
    background-origin: border-box;
    background-clip: border-area, text;
  }
}

@supports not (background-clip: border-area) {
  .text-wrapper {
    color: transparent;
    border: 2px solid #00257f;
    border-radius: 50px;
    background-image: linear-gradient(91deg, #e5000e 0%, #fc9f09 100%);
    background-origin: border-box;
    background-clip: text;
  }
}