- 方式1
div {
border: 4px solid;
border-image: linear-gradient(to right, #8f41e9, #578aef) 1;
}
/* 或者 */
div {
border: 4px solid;
border-image-source: linear-gradient(to right, #8f41e9, #578aef);
border-image-slice: 1;
}
作者:MudOnTire
链接:https://juejin.cn/post/7017701121619656711
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 方式2-5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=2.0" />
<title>Document</title>
</head>
<body>
<!-- 方式2 -->
<div class="border-box2 border-bg2">
<div class="content2">
方式2: 使用 background-image
绘制渐变色背景,并且把中间用纯色遮住应该是最容易想到的一种方法,思路是:使用两个盒子叠加,给下层的盒子设置渐变色背景和
padding,给上层盒子设置纯色背景。
</div>
</div>
<!-- 方式3 -->
<div class="border-box3">
<div class="border-bg3"></div>
<div class="content3">
为了解决方法 2 中 border-radius
不准确的问题,可以使用一个单独的元素作为渐变色背景放在最下层,上层设置一个透明的
border 和纯色的背景(需要设置 background-clip: padding-box
以避免盖住下层元素的 border), 上下两层设置相同的 border-radius。
</div>
</div>
<!-- 方式4 -->
<div class="border-box4">
<div class="content4">
我们可以使用伪元素替换 div.border-bg 以简化HTML结构。
</div>
</div>
<!-- 方式5 -->
<div class="border-box5">
<div class="content5">
最后是我觉得最优雅的一种方法,只需要用到单层元素,为其分别设置
background-clip、background-origin、background-image
这三个属性,每个属性设置两组值,第一组用于设置border内的单色背景,第二组用于设置border上的渐变色。
</div>
<style>
/* 方式2: */
.border-box2 {
width: 300px;
height: 200px;
margin: 25px 0;
}
.border-bg2 {
background: linear-gradient(to right, #9d63e0, #2c62eb);
padding: 20px;
border-radius: 25px;
}
.content2 {
height: 100%;
background-color: #fff;
border-radius: 10px; /*trciky part*/
}
/* 方式3 */
.border-box3 {
border: 4px solid transparent;
border-radius: 16px;
position: relative;
background-color: rgba(255, 255, 255, 1);
background-clip: padding-box; /*important*/
}
.border-bg3 {
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);
}
/* 方式4 */
.border-box4 {
border: 4px solid transparent;
border-radius: 16px;
position: relative;
background-color: rgba(255, 255, 255, 1);
background-clip: padding-box; /*important*/
}
.border-box4::after {
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);
}
/* 方式5 */
.border-box5{
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, #fff, #fff), linear-gradient(90deg, #8F41E9, #578AEF);
}
</style>
</body>
</html>
文章参考链接: https://juejin.cn/post/7017701121619656711