skip to Main Content

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?

2

Answers


  1. 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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search