方案一:双层元素,使用一个单独的元素作为渐变色背景放在最下层,上层设置一个透明的 border 和纯色的背景(需要设置 background-clip: padding-box 以避免盖住下层元素的 border), 上下两层设置相同的 border-radius
。
<div class="border-box">
<div class="content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste ratione necessitatibus numquam sunt nihil quos
saepe sit facere. Alias accusamus voluptate accusantium facere fugiat animi temporibus adipisci! Corporis,
accusamus tempora.
</div>
</div>
.border-box {
border: 4px solid transparent;
border-radius: 16px;
position: relative;
background-color: #222;
background-clip: padding-box; /*important*/
}
.border-box::before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
z-index: -1;
margin: -4px;
border-radius: inherit; /*important*/
background: linear-gradient(to right, #8F41E9, #578AEF);
}
方案二:单层元素,为其分别设置 background-clip
、background-origin
、background-image
这三个属性,每个属性设置两组值,第一组用于设置border内的单色背景,第二组用于设置border上的渐变色。
.border-box {
border: 4px solid transparent;
border-radius: 16px;
background-clip: padding-box, border-box;
background-origin: padding-box, border-box;
background-image: linear-gradient(to right, #222, #222), linear-gradient(90deg, #8F41E9, #578AEF);
}