Button边框 + 字体渐变(附代码)

436 阅读1分钟

代码demo地址

首先需要熟悉一个属性

  1. background-clip, 设置元素的背景(背景图片或颜色)是否延伸程度,text, content, border ,padding;

button 边框渐变

<h6>(原理即适用padding模拟border,PC, 移动端可利用缩放实现)</h6>
<button type="button" class="buttonB">
 1px渐变边框
</button>
.buttonB {
  background-clip: content-box, padding-box;
  padding: 1px;
  background-image: linear-gradient(white, white),
    linear-gradient(180deg, #7f74f8 0%, #7ac2fa 100%);
}

button 边框渐变 + 文字渐变

方案一: background-clip: text

        <button type="button" class="buttonD" desc="边框+文字渐变">
          边框+文字渐变
        </button>
.buttonD {
  background-clip: content-box, padding-box;
  padding: 1px;
  background-image: linear-gradient(white, white),
    linear-gradient(180deg, #7f74f8 0%, #7ac2fa 100%);
  position: relative;

  &::after {
    content: attr(desc);
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    -webkit-background-clip: text; /* 属性值,text兼容性差 */
    color: transparent;
    background-image: linear-gradient(180deg, #7f74f8 0%, #7ac2fa 100%);
  }
}

方案二: 内部的渐变字体使用svg绘制

html

<button type="button" class="buttonC" desc="边框+文字渐变">
 <svg>
   <defs>
     <linearGradient id="cool" x1="0%" y1="0%" x2="0%" y2="100%">
       <stop offset="0%" stopColor="#7F76F8 " stopOpacity="1" />
       <stop offset="100%" stopColor="#7EC4FA" stopOpacity="1" />
     </linearGradient>
   </defs>

   <text
     x="50%"
     y="50%"
     dy="2"
     fill={`url(#cool)`}
     style={{
       fontSize: "18px",
       alignmentBaseline: "middle",
       textAnchor: "middle"
     }}
   >
     边框+文字渐变
   </text>
 </svg>
</button>
.buttonC {
  background-clip: content-box, padding-box;
  padding: 1px;
  background-image: linear-gradient(white, white),
    linear-gradient(180deg, #7f74f8 0%, #7ac2fa 100%);
  position: relative;

  svg {
    width: 100%;
    height: 100%;
  }
}