仅为顶部和底部创建线性渐变边框?

5

使用下面的代码,我只能为元素的底部边缘生成一个线性渐变border-image。如何修改代码以使其也适用于顶部?

div {
    /* gradient shining border */
    border-style: solid;
    border-width: 3px;
    -webkit-border-image: -webkit-linear-gradient(
        left,
        rgba(0,0,0,1) 1%,
        rgba(0,255,255,1) 50%,
        rgba(0,0,0,1) 100%
    ) 0 0 100% 0/0 0 3px 0 stretch;
    -moz-border-image: -moz-linear-gradient(
        left,
        rgba(0,0,0,1) 1%,
        rgba(0,255,255,1) 50%,
        rgba(0,0,0,1) 100%
    ) 0 0 100% 0/0 0 3px 0 stretch;
    -o-border-image: -o-linear-gradient(
        left,
        rgba(0,0,0,1) 1%,
        rgba(0,255,255,1) 50%,
        rgba(0,0,0,1) 100%
    ) 0 0 100% 0/0 0 3px 0 stretch;
    border-image: linear-gradient(
        to left,
        rgba(0,0,0,1) 1%,
        rgba(0,255,255,1) 50%,
        rgba(0,0,0,1) 100%
    ) 0 0 100% 0/0 0 3px 0 stretch;
}

当前输出:

在此输入图片描述

2个回答

17

您正在使用简写的 border-image 属性来设置渐变方式的大小,根据提供的值,上、左和右边框被置空。

100% 设置为边框渐变的宽度,并将 3px 设置为其高度,会使渐变只在顶部和底部应用。

border-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%) 
              100% 0 100% 0/3px 0 3px 0 stretch;

在上述代码行中,100% 0 100% 0/3px 0 3px 0表示每个边框的渐变大小(按照[顶部] [右侧] [底部] [左侧]的顺序读取)。最初它是 0 0 100% 0/0 0 3px 0

div {
  /* gradient shining border */
  border-style: solid;
  border-width: 3px;
  border-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%) 
                100% 0 100% 0/3px 0 3px 0 stretch;
  
  /* other demo stuff */
  height: 50px;
  line-height: 50px;
  background-color: #222;
  color: white;
  text-align: center;  
}
<div>Some content</div>

请注意,border-image属性的浏览器支持率仍然相对较低,如果您需要支持IE10及以下版本,则无法使用该属性。相反,您可以像下面的代码片段中一样使用background-image来实现类似的效果。这也适用于IE10(但在IE9及以下版本中仍无法使用,因为它们根本不支持渐变)。


div {
  /* gradient shining border */
  background-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%), 
                    linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%);
  background-size: 100% 3px;
  background-position: 0% 0%, 0% 100%;
  background-repeat: no-repeat;
  
  /* other demo stuff */
  height: 50px;
  line-height: 50px;
  background-color: #222;
  color: white;
  text-align: center;
}
<div>Some content</div>


0

这应该可以工作:

...
border-style: solid;
border-width: 3px;
border-image: linear-gradient(90deg,
                rgba(0, 0, 0, 0),
                rgba(0, 255, 255, 1),
                rgba(0, 0, 0, 0))
                1 0;

border-image 是以下属性的简写形式:

border-image-source: #;
border-image-slice: #;
border-image-width: #;
border-image-outset: #;
border-image-repeat: #;

更多关于此内容的信息,您可以在border-image MDN中找到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接