Macmac Tan
Macmac Tan

Reputation: 101

Negative z index not working on ::after pseudo element

I do not get why the pseudo element ::after doesn't go behind the blue box when I put the z-index as a negative value with the other divs having no z-index values. As of the moment the blue box is behind the yellow box but I want the yellow box to be below the blue box but above the red one.

.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
}
<div class="menu1">
        <div class="menupicture1"></div>
</div>

Upvotes: 2

Views: 2727

Answers (3)

Chiller
Chiller

Reputation: 9738

use negative z-index on the red box and yellow box, and add position:relative; to them

.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
  position:relative;
  z-index: -1;
  
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;

}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  position:relative;
  z-index: -1;

}
<div class="menu1">
        <div class="menupicture1"></div>
</div>

Upvotes: 1

sol
sol

Reputation: 22949

You need to give elements a position.

more info

.menu1 {
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 1;
  position: relative;
}

.menu1 .menupicture1 {
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after {
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position: relative;
}
<div class="menu1">
  <div class="menupicture1"></div>
</div>

Upvotes: 1

LKG
LKG

Reputation: 4192

You are missing the position:absolute in pseudo element.

update css part below:

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position:absolute; /* add this property */
}

.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position:absolute;
}
<div class="menu1">
        <div class="menupicture1"></div>
</div>

Upvotes: 1

Related Questions