Search code examples
htmlcssz-index

Pseudo element with z-index: -1 is hidden by background-color


I have a .link class with an ::after pseudo element underneath it (as a box-shadow on hover).

.bg {
    background-color: aqua;
    height: 100vh;
}

.link {
    position: relative;
    font-weight: bold;
}

.link::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    box-shadow: 0 0 0 1em #888888 inset;
    opacity: 0;
}

.link:hover::after {
    opacity: 1;
}
<div class="bg">
  <p class="link">Link</p>
</div>

However, when I add a background-colour to the encompassing div element, it covers up the box-shadow. I have tried adding

position: absolute;
z-index: -2;

to the div but that causes a resizing issue with the div, although the stacking is correct. I wonder if there's a preferred method to place a pseudo element above the bg layer but behind the original link class? Thanks!


Solution

  • Add z-index:0 (or any value) to the background element in order to create a stacking content and avoid the pseudo element moving behind:

    .bg {
        background-color: aqua;
        height: 100vh;
        position:relative;
        z-index:0; /* added */
    }
    
    .link {
        position: relative;
        font-weight: bold;
    }
    
    .link::after {
        content: '';
        position: absolute;
        z-index: -999; /*you can put any negative value now*/
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        box-shadow: 0 0 0 1em #888888 inset;
        opacity: 0;
    }
    
    .link:hover::after {
        opacity: 1;
    }
    <div class="bg">
      <p class="link">Link</p>
    </div>

    Related: Why elements with any z-index value can never cover its child?