1

I am trying to create two-colored border with pseudo-element. But if I add z-index to the parent ".d" it stops working. Is there a way to have "position: relative" and "z-index" on ".d" and make this work?

.d {
  background-color: #000;
  height: 100px;
  width: 100px;
  /*z-index: 1000;  */
  /* Stops working if I add z-index */
  position: relative;
}
.d:before {
  content: "";
  border: #0000ff 4px dashed;
  background-color: #ff0000;
  top: -2px;
  left: -2px;
  bottom: -2px;
  right: -2px;
  position: absolute;
  z-index: -1;
}
<div class="d"></div>

https://jsfiddle.net/vmwm0zfg/

misterManSam
  • 24,303
  • 11
  • 69
  • 89
Bob
  • 5,809
  • 5
  • 36
  • 53
  • could you give an expected image for me? – Thi Tran Jul 17 '15 at 10:41
  • You might also be interested in [this question which has a few methods to create your own custom borders with greater control over their appearance cross browser](http://stackoverflow.com/q/2771171/2930477) – misterManSam Jul 17 '15 at 14:53

1 Answers1

2

You can use two pseudo elements one with a solid border and one with the dashed. The solid border sits underneath the dashed border eliminating the need for negative z-index.

overflow: hidden can be used on the parent to cut the borders width whilst maintaining the stroke length.

.d {
  background-color: #000;
  height: 100px;
  width: 100px;
  position: relative;
  z-index: 100;
  /*Hidden is to cut off the excess border*/
  overflow: hidden;
}
.d:before,
.d:after {
  content: "";
  top: -2px;
  left: -2px;
  bottom: -2px;
  right: -2px;
  position: absolute;
}
.d:before {
  border: #F00 4px solid;
}
.d:after {
  border: #00a3ff 4px dashed;
}
<div class="d"></div>
misterManSam
  • 24,303
  • 11
  • 69
  • 89