border-image

学习文档

上文中未提及:

边框渐变

假设要实现一个边框从上到下的渐变效果,如图所示:

边框渐变效果图

其中,

  • 边框的渐变由上#9a5eff到下#702ff3
  • 内容区背景是blue,元素外的背景是#1d0277(只是为了能让边框渐变显示地更加清楚,与边框渐变实现无关)。
  • 圆角border-radius: 16px

补充:掘金 - 巧妙实现带圆角的渐变边框open in new window 这篇文章说的更加详细,实现方式更多。

实现方式一:border-image

<div class="background">
    <div class="example first-example"></div>
</div>
1
2
3
.background {
    padding: 20px;
    background: #1d0277;
    .example {
        width: 700px;
        height: 30px;
        &.first-example {
            border: 2px solid;
            border-radius: 16px;
            border-image: linear-gradient(180deg,#6c41eb 0%, #611dcf 100%) 2;
            background: blue;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

可以发现,尽管我们能用border-image+linear-gradient实现了边框渐变,但是border-radius却失效了。

W3C 的规范里明确指出,border-image不受border-radius影响。

A box's backgrounds, but not its border-image, are clipped to the appropriate curve (as determined by ‘background-clip’).

CSS Backgrounds and Borders Module Level 3 - W3C Working Draft 12 June 2010 - 4.4.2. Corner Clippingopen in new window

Although border images are not affected by border-radius... CSS Backgrounds and Borders Module Level 3open in new window

实现方式二:background*2

.background {
    padding: 20px;
    background: #1d0277;
    .example {
        width: 700px;
        height: 30px;
        &.second-example {
            padding: 2px;
            border-radius: 16px;
            background: linear-gradient(180deg,#6c41eb 0%, #611dcf 100%);
            .inner-second {
                width: 100%;
                height: 100%;
                border-radius: 16px;
                background: blue;
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

效果演示

实现方式一:border-image

实现方式二:border-image*2