CSS中有4个渐变边框

rah*_*tel 4 html css border linear-gradients css3

我需要帮助在的所有4个边上应用渐变边框.我尝试过,但它只适用于双方.在查看所有链接和SO答案后,我得到了这个:

.test{
  height:250px;
  border: 2px solid;
  border-image: linear-gradient(to left,rgba(78,137,176,1)  1%, rgba(115,192,85,1)  100%) 100% 0 100% 0/2px 0 2px 0;
  padding-top:50px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="test">
  This is a box and I want borders for all the sides
</div>
Run Code Online (Sandbox Code Playgroud)

我将不胜感激任何帮助.我正在尝试类似于下图的内容.谢谢.

在此输入图像描述

Har*_*rry 12

使用背景图像:(产生精确的输出作为图像)

您似乎每侧都有不同的渐变,因此很难通过该border-image属性实现此目标.您可以尝试使用background-image以下代码段中的行为来模仿行为.

基本上下面的代码片段的作用是它为4个边中的每一个创建渐变作为渐变背景图像条,然后用于background-position将它们放置在正确的位置.

父级上的透明边框是一个占位符,模仿的边框最终会出现.在background-origin: border-box使该元素的背景从启动border-box区本身(而不是padding-boxcontent-box).这两个只是额外的步骤,以避免使用不必要的calc东西background-position.

.test {
  height: 250px;
  border: 2px solid transparent;
  background-image: linear-gradient(to right, rgb(187, 210, 224), rgb(203, 231, 190)), linear-gradient(to bottom, rgb(114, 191, 87), rgb(116, 191, 86)), linear-gradient(to left, rgb(204, 233, 187), rgb(187, 210, 224)), linear-gradient(to top, rgb(84, 144, 184), rgb(80, 138, 176));
  background-origin: border-box;
  background-size: 100% 2px, 2px 100%, 100% 2px, 2px 100%;
  background-position: top left, top right, bottom right, bottom left;
  background-repeat: no-repeat;
  padding-top: 50px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="test">
  This is a box and i want border for all the side
</div>
Run Code Online (Sandbox Code Playgroud)


使用边框图像:(在所有4个边上生成边框但与图像输出的输出不同)

您可以使用border-image属性获得的最佳输出如下所示,但从演示中可以看出它与您的图像(或第一个片段的输出)不完全相同:

.test {
  height: 250px;
  border: 2px solid;
  border-image: linear-gradient(to left, rgba(78, 137, 176, 1) 1%, rgba(115, 192, 85, 1) 100%);
  border-image-slice: 1;
  padding-top:50px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="test">
  This is a box and i want border for all the side
</div>
Run Code Online (Sandbox Code Playgroud)

  • @rahulpatel:这里实际上差别不大.`border-image`是用于创建边框渐变的推荐属性,但它不会产生您需要的输出,因此我们只能使用替代方法.使用`background-image`并没有错(我知道语义是明智的,但这是另一回事).唯一的问题是,如果元素实际上有一个渐变/图像***背景***,那么我们需要在放置它时要格外小心.但这可以使用相同的属性(`background-origin`,`background-position`)+一个额外的`background-clip`来完成.这不是不可能的:) (2认同)