本文摘自PHP中文网,作者青灯夜游,侵删。

CSS如何实现带圆角的渐变边框?下面本篇文章给大家介绍一下使用CSS巧妙实现带圆角的渐变边框的几种方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
如何实现下面这个渐变的边框效果:
这个问题本身不难,实现的方法也有一些,主要是有一些细节需要注意。
border-image
border-image
是 CSS 规范 CSS Backgrounds and Borders Module Level 3 (最新一版的关于 background 和 border 的官方规范) 新增的一个属性值。
顾名思义,我们可以给 border 元素添加 image,类似于 background-image
,可以是图片也可以是渐变,不再局限于纯色。
使用 border-image 实现渐变边框
有了 border-image
之后,实现渐变边框变得很方便
不过多介绍 border-image 的语法,读者需要自行了解一下。
实现如下:
1 |
|
1 2 3 4 5 6 7 8 |
|
上面关于 border-image 的三个属性可以简写为 border-image: linear-gradient(45deg, gold, deeppink) 1;
得到如下结果:
border-radius 失效
仔细看上面的 Demo,设置了 border-radius: 10px
但是实际表现没有圆角。使用 border-image
最大的问题在于,设置的 border-radius
会失效。
我们无法得到一个带圆角的渐变边框。原因,查看官方规范 W3C 解释如下:
A box's backgrounds, but not its border-image, are clipped to the appropriate curve (as determined by ‘background-clip’). Other effects that clip to the border or padding edge (such as ‘overflow’ other than ‘visible’) also must clip to the curve. The content of replaced elements is always trimmed to the content edge curve. Also, the area outside the curve of the border edge does not accept mouse events on behalf of the element.
为此,我们得另辟蹊径或者稍加改进,得到带圆角的渐变边框。
法一:background-image + 伪元素
第一种方法,我们不再使用 border-image
,而是使用 background-image
+ 伪元素 的方案,这也是在 border-image
规范没有出现最常用的方法。
非常简单,简单的示意图如下:
利用 background-image
实现一个渐变背景,再通过叠加一个白色背景使之形成一个渐变边框。
CodePen Demo -- bg + overflow 实现渐变边框
缺点
这个方案有两个问题,第一个是多使用了两个元素(当然在这里是 ::before 和 ::after),其次最致命的是,如果要求边框?鹊谋尘笆峭该鞯模?此方案便行不通了。
法二,使用 background-clip 实现
第二种方法,使用 background-clip: content-box
以及 background-clip: border-box
配合使用。
background-clip:background-clip 设置元素的背景(背景图片或颜色)是否延伸到边框下面。它的部分取值和 box-sizing
类似。其中,
background-clip: border-box
表示设置的背景background-image
将延伸至边框background-clip: content-box
表示设置的背景background-image
被裁剪至内容区(content box)外沿
这里,我们使用设置两个 background-image
,设置两个 background-clip
,并且将 border 设置为透明即可:
核心 CSS:
1 2 3 4 5 6 7 8 9 10 |
|
因为用到了 background-clip: border-box
,所以还需要 background-origin: border-box
使图案完整显示,可以尝试下关掉这个属性,即可明白为什么需要这样做。
CodePen Demo -- background-clip 实现渐变边框
缺点
相关阅读 >>
dreamweaver网页怎么创建css样式的复合声明?_dreamweaver教程_网页制作
更多相关阅读请进入《css》频道 >>

Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者