如何使用CSS创建多彩边框?

40
如何创建像下面图片那样的多彩边框?

在此输入图片描述


1
http://jsfiddle.net/yH59y/ - Roysh
2
您可以使用边框图像:http://www.w3schools.com/cssref/css3_pr_border-image.asp - Andrew
1
尝试一下这个:http://www.hongkiat.com/blog/css-gradient-border/ - Sanjeev Kumar
3个回答

75

您可以使用border-image: linear-gradient 而不需要伪元素来实现。

.fancy-border {
  width: 150px;
  height: 150px;
  text-align:center;
  border-top: 5px solid;
  border-image:   linear-gradient(to right, grey 25%, yellow 25%, yellow 50%,red 50%, red 75%, teal 75%) 5;
}
<div class="fancy-border">
  my content
</div>


7
这应该是最佳答案,比目前被接受的答案更加简洁。 - Erick
如何只用三种颜色完成它? - user1971598
2
@EdgarAroutiounian 只需编辑百分比以匹配即可。 如果您只想要3种颜色,则将“100%/ 3”除以33.33%。 而不是25%,然后指定“33%”等等,这样您就只有三种颜色了。 - Rasmus Lauridsen
3
border-image 行末的 5 是什么意思? - vik
1
@vik 我认为是切片参数,https://www.w3schools.com/cssref/css3_pr_border-image-slice.asp - Theodore K.

46

您可以使用 :after:before 伪元素和 css 的 linear-gradient 来实现,如下所示:

body {
  background: #ccc;
}

.box {
  text-align: center;
  position: relative;
  line-height: 100px;
  background: #fff;
  height: 100px;
  width: 300px;
}

.box:after {
  background: linear-gradient(to right, #bcbcbc 25%,#ffcd02 25%, #ffcd02 50%, #e84f47 50%, #e84f47 75%, #65c1ac 75%);
  position: absolute;
  content: '';
  height: 4px;
  right: 0;
  left: 0;
  top: 0;
}
<div class="box">Div</div>


1
尝试一下。

.test {
  width: 500px;
  height: 100px;
  background-color: #ccc;
  position: relative;
}

.test:before,
.test:after {
  content: "";
  position: absolute;
  left: 0px;
  right: 0px;
  height: 10px;
  background-image: -webkit-linear-gradient(0deg, red 20px, blue 20px, blue 40px, yellow 40px, yellow 60px, green 60px, green 80px);
  background-image: -ms-linear-gradient(0deg, red 20px, blue 20px, blue 40px, yellow 40px, yellow 60px, green 60px, green 80px);
  background-size: 80px;
}

.test:before {
  top: 0px;
}

.test:after {
  bottom: 0px;
}
<div class="test"></div>


这只是评论中的链接吗? - Magesh Kumaar
对于 Firefox:-webkit-border-image: -webkit-gradient(linear, left top, left bottom, from(#00abeb), to(#fff), color-stop(0.5, #fff), color-stop(0.5, #66cc00)) 21 30 30 21 repeat repeat; - Neeraj Prajapati

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