如何仅为顶部和底部使用线性渐变边框?

时间:2015-09-01 10:43:14

标签: html css css3 border linear-gradients

使用下面的代码,我只能为其底部生成线性渐变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;
}

当前输出:

enter image description here

1 个答案:

答案 0 :(得分:9)

您正在使用简写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表示每边的渐变边框的大小(读作[top] [right] [bottom] [left])。最初是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 property still has pretty low browser support如果您需要支持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>