Search code examples
csscss-selectorspseudo-element

Cant position ::before Pseudo Element behind its parent


I tried to create a div, and have its ::before appear behind it to make it seem as some sort of shadow, but for some reason I cant get the pseudoelement to appear behind the original element.

<div class="hero container split">
                <div class="hero__cont-image bg-dark"><img src="" alt="" class="hero_cont-image__image">
                </div>
.hero__cont-image {
  position: relative;
  transform: rotate(0);
  display: flex;
  align-items: center;
  justify-content: center;
  left: calc(-50vw + 50%);
  border-radius: 0px 300px 300px 0px;
}

.hero__cont-image::before {
  content: "";
  background-color: blue;
  position: absolute;
  width: 125%;
  height: 125%;
  z-index: -1;
}

I want the pseudo element to appear behind the original element


Solution

  • On the parent div transform will create a new stacking context making the parent div the root element of the stacking context. A stacking context’s root element will always be the lowest, even behind elements with negative z-index. The psuedo-element can't lower itself to be below the root element even with negative z-index, hence will always be above the background.

    If your are not using transform remove it and the pseudo element with negative z-index will appear to be below the parent since now the parent is not the root element of their stacking context anymore.

    .hero__cont-image {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      left: calc(-50vw + 50%);
      border-radius: 0px 300px 300px 0px;
    }
    
    .hero__cont-image::before {
      content: "";
      background-color: blue;
      position: absolute;
      width: 125%;
      height: 125%;
      z-index: -1;
    }
    <head>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    </head>
    
    <body>
      <div class="hero container split">
        <div class="hero__cont-image bg-dark"><img src="https://i.sstatic.net/memI0.png">
        </div>
      </div>
    </body>

    Note: These elements creates new stacking context: Opacity,transforms, filters, css-regions, paged media. If you need to rotate the parent element, create a wrapper div on the div and apply the transforms on the wrapper instead.