纯CSS渐变圆圈边框

Pure CSS gradient circle border

我有这个 UI 要求

目前,我有一个 div 的工作解决方案(具有固定的高度和宽度以及外部渐变边框的背景图像)和一个伪元素,定位 absolute 与内边框的背景图片。

.div {
    position: relative;
    width: 254px;
    height: 254px;
    border: 2px solid transparent;
    border-radius: 50%;
    background: url(../img/gradient_border_circle.png) no-repeat 50%;
}
div:before {
    content: "";
    position: absolute;
    top: 50%;
    transform: translate(-50%,-50%);
    left: 50%;
    width: 98px;
    height: 98px;
    border-radius: 50%;
    background: url(../img/gradient_border_circle_inner.png) no-repeat 50%;
}

但是,我正在寻找一种更优雅的解决方案(纯 css 或 svg 渐变?)而不使用背景图像,其中渐变可以在没有像素化的情况下缩放。

我已经研究过,我遇到的最接近的是 https://codepen.io/nordstromdesign/pen/QNrBRM and Possible to use border-radius together with a border-image which has a gradient? 但我需要一个中心透明的解决方案,以便通过页面的背景显示

更新:理想情况下,我正在寻找一种在所有现代浏览器中都具有相对良好支持的解决方案。

您可以使用 mask 来实现您想要的。您将需要一个带有透明圆圈的 SVG 文件。这里我使用了网上的图片,但是你可以根据自己的需要制作自己的图片:

mask: url(circle.svg);

SVG 是创建圆形并在其周围绘制渐变轮廓/边框的推荐方法。

SVG 有一个 circle 元素可用于绘制圆形。此形状可以用纯色、渐变或图案填充和勾勒轮廓。

* {box-sizing: border-box;}

body {
  background: linear-gradient(#333, #999);
  text-align: center;
  min-height: 100vh;
  padding-top: 10px;
  margin: 0;
}
svg {vertical-align: top;}
<svg width="210" height="210">
  <defs>
    <linearGradient id="grad1" x1="0" y1="1" x2="1" y2="0">
      <stop offset="0" stop-color="#f5d700" />
      <stop offset="1" stop-color="#0065da" />
    </linearGradient>
    <linearGradient id="grad2" xlink:href="#grad1" x1="1" y1="0" x2="0" y2="1"></linearGradient>
  </defs>
  <g fill="none">
    <circle cx="100" cy="100" r="95" stroke="url(#grad1)" stroke-width="2" />
    <circle cx="100" cy="100" r="40" stroke="url(#grad2)" stroke-width="5" />
  </g>
</svg>

这是一个仅适用于 CSS 的解决方案,应该可以在所有现代浏览器中正常工作(在 Chrome、Firefox 和 Edge 上测试)

.box {
  --it:20px; /* thickness of inner gradient */
  --ot:10px; /* thickness of outer gradient */
  --s:30%;   /* starting point of inner gradient */

  width:200px;
  display:inline-flex;
  box-sizing:border-box;
  border-radius:50%;
  border:var(--ot) solid transparent;
  background:
      /* inner gradient clipped to the padding area */
      conic-gradient(red,blue,green,red) padding-box,
      /* outer gradient visible on the border area */
      conic-gradient(purple,yellow,orange,purple) border-box;
      
  -webkit-mask:radial-gradient(farthest-side,
    transparent var(--s), 
    #fff   calc(var(--s) + 1px)  
           calc(var(--s) + var(--it)),
    #fff0  calc(var(--s) + var(--it) + 1px) 
           calc(100% - var(--ot)), 
    #fff   calc(100% - var(--ot) + 1px));
}
/* keep the ratio */
.box::before {
  content:"";
  padding-top:100%;
}

body {
  background:pink;
}
<div class="box"></div>
<div class="box" style="--s:5%;--ot:20px;width:150px;"></div>
<div class="box" style="--s:calc(100% - 20px);--it:10px;width:220px;"></div>
<div class="box" style="--s:0%;--it:50%;width:80px;"></div>

我在计算中添加 1px 以避免锯齿状边缘。您可以将 conic-gradient() 替换为另一种类型的渐变甚至图像