2024-02-03 07:00:02

梯度边界

我试图应用一个渐变的边界,我认为这是简单的这样做:

border-color: -moz-linear-gradient(top, #555555, #111111);

但这并不奏效。

有人知道做边界渐变的正确方法吗?


当前回答

最直接的方法是使用border-image属性。你可以使用任何你想要的线性渐变或重复渐变。对于线性梯度,边界图像切片属性需要为1。

.gradient-border {
    border-style: solid;
    border-width: 2px;
    border-image: linear-gradient(45deg, red, blue) 1;
}

参考文献 MDN - https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-slice 数字海洋- https://www.digitalocean.com/community/tutorials/css-gradient-borders-pure-css

其他回答

你可以在不使用background, background-clip和background-origin删除边界半径的情况下实现这一点:

<时尚> .border-gradient-rounded { /* Border */ 边框:4px实体透明; border - radius: 20 px; 背景: 线性渐变(向右,白色,白色), 线性梯度(右,红,蓝); 背景剪辑:填充盒、边框盒; 背景-起源:填充盒,边框盒; /*其他样式*/ 宽度:100 px; 高度:40像素; 填充:12 px; } > < /风格 < div class = " border-gradient-rounded”> 内容 < / div >

基本上,这将白色背景放置在渐变背景上,从内部边界剪辑白色背景,并从外部边界剪辑渐变背景。这就是为什么你需要将边框定义为纯透明的。

此dev.to post的功劳归于方法2。

我同意szajmon的观点。他和昆汀回答的唯一问题是跨浏览器兼容性。

HTML:

<div class="g">
    <div>bla</div>
</div>

CSS:

.g {
background-image: -webkit-linear-gradient(300deg, white, black, white); /* webkit browsers (Chrome & Safari) */
background-image: -moz-linear-gradient(300deg, white, black, white); /* Mozilla browsers (Firefox) */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#000000', gradientType='1'); /* Internet Explorer */
background-image: -o-linear-gradient(300deg,rgb(255,255,255),rgb(0,0,0) 50%,rgb(255,255,255) 100%); /* Opera */
}

.g > div { background: #fff; }

这里有一篇很好的css技巧文章:https://css-tricks.com/gradient-borders-in-css/

我能够想出一个非常简单的,单元素的解决方案,使用多个背景和background-origin属性。

.wrapper {
  background: linear-gradient(#222, #222), 
              linear-gradient(to right, red, purple);
  background-origin: padding-box, border-box;
  background-repeat: no-repeat; /* this is important */
  border: 5px solid transparent;
}

这种方法的优点是:

它不受z指数的影响 它可以通过改变透明边框的宽度来轻松缩放

去https://codepen.io/AlexOverbeck/pen/axGQyv?editors=1100看看吧

渐变边框来自Css-Tricks: http://css-tricks.com/examples/GradientBorder/

.multbg-top-to-bottom {
  border-top: 3px solid black;
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#000), to(transparent));
  background-image: -webkit-linear-gradient(#000, transparent);
  background-image:
      -moz-linear-gradient(#000, transparent),
      -moz-linear-gradient(#000, transparent);
  background-image:
      -o-linear-gradient(#000, transparent),
      -o-linear-gradient(#000, transparent);
  background-image: 
      linear-gradient(#000, transparent),
      linear-gradient(#000, transparent);
  -moz-background-size: 3px 100%;
  background-size: 3px 100%;
  background-position: 0 0, 100% 0;
  background-repeat: no-repeat; 
}

试试下面的例子:

.border-gradient {
      border-width: 5px 5px 5px 5px;
      border-image: linear-gradient(45deg, rgba(100,57,242,1) 0%, rgba(242,55,55,1) 100%);
      border-image-slice: 9;
      border-style: solid;
}