Home  >  Article  >  Web Front-end  >  ## How to Position a `::before` Pseudo-Element Behind Its Parent When Using `z-index`?

## How to Position a `::before` Pseudo-Element Behind Its Parent When Using `z-index`?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 20:59:02110browse

## How to Position a `::before` Pseudo-Element Behind Its Parent When Using `z-index`?

Z-Index Conundrum with Before Pseudo-Element

When employing a before pseudo-element within a parent element, it's essential to address its positioning behavior. By default, the pseudo-element is positioned inside its parent.

However, assigning a z-index to the parent element creates a new stacking context, isolating its contents. As a result, the before pseudo-element, even with a negative z-index, cannot appear behind the parent due to the stacking context boundary.

To address this, consider the following solution:

  1. Separate Element Hierarchy: Precede the header element with another element. This creates a natural stacking order where the new parent element can be given a z-index lower than the header, allowing the before pseudo-element to appear behind it.
  2. Z-Index Nesting: While less recommended, you can use negative z-index values for the pseudo-element and positive values for the parent element to create a desired stacking order within the same stacking context. However, this approach can lead to more complex code and potential cross-browser compatibility issues.

Example:

<code class="css"><div class="wrapper">
  <header>
    content...
    <span class="pseudo-element">Before content...</span>
  </header>
</div>

.wrapper {
  position: relative;
  z-index: 0;
}

header {
  position: relative;
  background: yellow;
  height: 100px;
  width: 100px;
  z-index: 1;
}

.pseudo-element {
  position: absolute;
  background: red;
  height: 100px;
  width: 100px;
  top: 25px;
  left: 25px;
  z-index: 0;
}</code>

The above is the detailed content of ## How to Position a `::before` Pseudo-Element Behind Its Parent When Using `z-index`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn