CSS如何实现带圆角的渐变边框?
做需求的时候发现蓝湖上面有个样式是实现渐变色边框但是边框有圆角。
然后我从蓝湖上面拷贝的代码是:
width: 558px;
height: 66px;
border-radius: 12px 12px 12px 12px;
border: 1px solid;
border-image: linear-gradient(99deg, rgba(50, 113, 204, 1), rgba(15, 255, 255, 1)) 1 1;
直接使用,居然没有圆角。我寻思我自己加个border-radius得了,然后还是不生效。
OK, 行!我自己去看看border-image是何方神圣,于是我在w3school上面查了一下。
border-image 属性是一个简写属性,用于设置以下属性:
如果省略值,会设置其默认值。
提示:请使用 border-image-* 属性来构造漂亮的可伸缩按钮!
实例
将图片规定为包围 div 元素的边框:
div
{
-webkit-border-image:url(border.png) 30 30 round; /* Safari 5 */
-o-border-image:url(border.png) 30 30 round; /* Opera */
border-image:url(border.png) 30 30 round;
}
CSS 语法
border-image: source slice width outset repeat|initial|inherit;
属性值
| 值 | 描述 | 测试 |
|---|---|---|
| border-image-source | 用在边框的图片的路径。 | |
| border-image-slice | 图片边框向内偏移。 | |
| border-image-width | 图片边框的宽度。 | |
| border-image-outset | 边框图像区域超出边框的量。 | |
| border-image-repeat | 图像边框是否应平铺(repeated)、铺满(rounded)或拉伸(stretched)。 | 测试 |
技术细节
| 默认值: | none 100% 1 0 stretch |
|---|---|
| 继承性: | no |
| 版本: | CSS3 |
| JavaScript 语法: | object.style.borderImage="url(border.png) 30 30 round" |
好家伙,意思是以后边框都可以自定义了。但是还是没搞清楚为啥border-radius失效,于是在W3C上面查了一下border-image的标准:
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.
总结就是:如果使用border-image给border填充颜色了,那border-radius的裁剪效果就会失效了。
那行吧,这个行不通就想其他办法呗。
- 首先我就想到既然这个是自适应边框,那当然可以让UI出一个渐变色的边框图,直接带上圆角就得了。当然我没好意思麻烦UI啦,于是只能换种思路。
- 然后第二个思路就是可以分两层嘛,第一层用background属性设置渐变色背景再加上圆角。第二层就用background属性加上需要的颜色把下面那层盖住,下面那层视觉上就只剩一个渐变色的圆角边框了,就能实现渐变色圆角边框了。然后我就用这种方式实现了。
- 但是后来我感觉这样太麻烦了,于是就在查了一下这个问题其他人怎么解决的,果真查到了一个更好的方式:
border: 1px solid transparent;
border-radius: 8px;
background-clip: padding-box, border-box;
background-origin: padding-box, border-box;
background-image: linear-gradient(to right, #1C1D2A, #1C1D2A),
linear-gradient(to right, #3271CC, #0FFFFF);
得,还是第二种方式那个思路解决的,但是方便不少。
因此记录一下,下次遇见了直接CV。