Pseudo elements get hidden when parent uses background

Viewed 53

When I apply a :before or :after pseudo element, this one gets hidden if the parent element uses a background.

You can notice that on this picture, where the red elements gets hidden behind the yellow background. Unlike its parent, the blue element.

enter image description here

.parent {
  background: yellow;
}

#element {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: blue;
  border: 4px solid black;
}

#element::after {
  content: "";
  width: 150px;
  height: 150px;
  background-color: red;

  position: absolute;
  z-index: -1;
  border: 4px solid black;
}
<div class="parent">
  <div id="element"></div>
</div>

Reproduction online: https://jsfiddle.net/subkrovy/

Any way to go around this?

1 Answers

You could translate the parent in the negative z axis. I'm not sure if that's an option for your overall project but in this context, it works.

.parent {
  background: yellow;
  transform: translateZ(-1px)
}

#element {
  position: relative;
  /* optional */
  width: 100px;
  height: 100px;
  background-color: blue;
}

#element::after {
  content: "";
  width: 150px;
  height: 150px;
  background-color: red;
  /* create a new stacking context */
  position: absolute;
  z-index: -1;
  /* to be below the parent element */
}
<div class="parent">
  <div id="element"></div>
  <div id="yellow"></div>
</div>

z-index edition because why not:

.parent {
  background-color: yellow;
  width: 100%;
  position: absolute;
  z-index: -2;
}

#element {
  position: relative;
  /* optional */
  width: 100px;
  height: 100px;
  background-color: blue;
}

#element::after {
  content: "";
  width: 150px;
  height: 150px;
  background-color: red;
  /* create a new stacking context */
  position: absolute;
  z-index: -1;
  /* to be below the parent element */
}
<div class="parent">
  <div id="element"></div>
  <div id="yellow"></div>
</div>

Related