Search code examples
cssz-index

Pseudo element: proper z-index stacking context?


I have two DIV elements on the same level: bar and nav with ::before pseudo element.

That nav and bar should appear under ::before pseudo element but text within nav above it, something like this:

|- nav text
   |- nav pseudo element
      |- bar

*,
*::after,
*::before {
  box-sizing: border-box;
  margin: 0;
}
header {
  position: relative;
}
.bar {
  color: white;
  background-color: black;
}
.nav {
  background-color: orange;
}
p {
  color: white;
  margin-left: 10%;
}
.nav::before {
  z-index: 0;
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 40%;
  bottom: 0;
  height: 0;
  border-style: solid;
  border-width: 4rem 4rem 0 0;
  border-color: green transparent transparent transparent;
}
<header>
  <div class="bar">bar that should remain under green</div>
  <div class="nav">
    <p>text that should appear above green</p>
  </div>
</header>


Solution

  • Just add the same properties to text.

    *,
    *::after,
    *::before {
      box-sizing: border-box;
      margin: 0;
    }
    header {
      position: relative;
    }
    .bar {
      color: white;
      background-color: black;
    }
    .nav {
      background-color: orange;
    }
    p {
      color: white;
      margin-left: 10%;
      z-index: 1;
      position: relative;
    }
    .nav::before {
      z-index: 0;
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 40%;
      bottom: 0;
      height: 0;
      border-style: solid;
      border-width: 4rem 4rem 0 0;
      border-color: green transparent transparent transparent;
    }
    <header>
      <div class="bar">bar that should remain under green</div>
      <div class="nav">
        <p>text that should appear above green</p>
      </div>
    </header>