0

Is it possible to use a before element for an overlay background on a nav, like this?

.nav {
  background: white;
  position: fixed;
}

.nav::before {
  content: '';
  background: black;
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
<nav class="nav">
  Nav content
</nav>

The issue I have is that the black overlay sits above the white nav, yet I want it behind? How can this be fixed?

panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

1

This can easily be achieved with isolation: isolate along with a suitable positioning and z-index on the pseudo-element:

.nav {
  /* to have the text stand out clearly */
  color: #fff;
  /* an easily-seen background for contrast
     in the demo: */
  background: #f00;
  /* just to better illustrate: */
  padding: 1rem;
  /* in order that the descendant pseudo-element
     is positioned in relation to this one:*/
  position: relative;
  /* to contain the stacking within the element,
     so that z-index: -1 on the pseudo-element
     doesn't place that pseudo-element behind
     its parent: */
  isolation: isolate;
}

.nav::before {
  content: '';
  /* for easy contrast for demonstration: */
  background-image: linear-gradient(90deg, transparent, black);
  /* in order to move the element out of
     the document flow, and to be positioned: */
  position: absolute;
  /* using 'inset' in place of 'top','right', 'bottom'
     and 'left': */
  inset: 0;
  z-index: -1;
}
<nav class="nav">
  Nav content
</nav>
David Thomas
  • 249,100
  • 51
  • 377
  • 410
-2

Try to use z-index, i hope that its help you :)

.nav {
      background: white;
          z-index:1;
}

.nav::before {
    content:"";
    background: black;
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    z-index:-1;
}
<nav class="nav">
    Nav content
</nav>
Yarin Levi
  • 201
  • 1
  • 10