0

z-index: -1 for the :before is not working when specifying z-index:2 for the box.

How to move the :before below the box keeping the z-index:2 for the box.

.box{
  background: lavender;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2;
}
.box:before{
  content: '';
  width: 100%;
  height: 100%;
  border: 1px solid #000;
  position: absolute;
  right: -20px;
  bottom: -20px;
  z-index: -1;
}
<div class="box">
</div>

Fiddle - https://jsfiddle.net/gLnfde49/

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Felix A J
  • 6,300
  • 2
  • 27
  • 46

2 Answers2

0

.box {
  background: lavender;
  height: 200px;
  width: 200px;
  position: relative;
}
.box::before {
  content: "";
  display: block;
  height: 100%;
  width: 100%;
  border: 1px solid #000;
  position: absolute;
  z-index: -1;
  right: -20px;
  bottom: -20px;
}
.main
{
  content: "";
  display: block;
  width: 100%;
  position: absolute;
  right: 50;
  transform : translate(50%,50%);
}
<div class="main">
  <div class="box">
</div>
</div>

I have achieved this using the ::before element and used the main element as position:relative;. To make the div of class .box to be in middle of the page add a div above (.main) if needed.

Haerriz
  • 145
  • 2
  • 9
-1

Issue is with transform property and you need to relative parent for absolute child

.box {
    background: lavender;
    height: 200px;
    width: 200px;
    position: relative;
    /* left: 50%; */
    /* transform: translateX(-50%); */
    /* z-index: 2; */
    margin: 0 auto;
}
Awais
  • 4,752
  • 4
  • 17
  • 40