Bob
Bob

Reputation: 6173

How to position :before pseudo element under parent that has z-index + position relative set?

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/

Upvotes: 1

Views: 1778

Answers (1)

misterManSam
misterManSam

Reputation: 24702

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>

Upvotes: 2

Related Questions