Search code examples
cssbox-shadow

Box shadow of "translated" box falls on sibling box


Box shadow of the box falls on the sibling box. I can use z-index to fix it. However, if one of the boxes is translated (e.g. move a little bit up when mouse over), the shadow falls the sibling again. How to solve this? Thanks.

.container {
  margin: 30px;
  padding: 10px;
}

div.shadow {
  height: 100px;
  width: 100px;
  background-color: #ff0;
  float: left;
  margin: 4px;
}

.shadow {
  position: relative;
}

.shadow:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  box-shadow: 0px 10px 1000px #000;
}

.shadow:hover {
  transform: translateY(-3px);
}

.shadow:hover::after {
  box-shadow: 0px 20px 1500px #000;
}
<div class="container">
  <div class="shadow"></div>
  <div class="shadow"></div>
  <div class="shadow"></div>
  <div class="shadow"></div>
</div>


Solution

  • When you use translate on parent, you create a new stacking context, that places the transformed .shadow element on top of it's siblings. To prevent that you can use other properties than transform (top: -3px for example):

    .container {
      margin: 30px;
      padding: 10px;
    }
    
    .shadow {
      position: relative;
      height: 100px;
      width: 100px;
      background-color: #ff0;
      float: left;
      margin: 4px;
    }
    
    .shadow::after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      z-index: -1;
      box-shadow: 0px 10px 1000px #000;
    }
    
    .shadow:hover {
      top: -3px;
    }
    
    .shadow:hover::after {
      box-shadow: 0px 20px 1500px #000;
    }
    <div class="container">
      <div class="shadow"></div>
      <div class="shadow"></div>
      <div class="shadow"></div>
      <div class="shadow"></div>
    </div>