Search code examples
htmlcssz-index

CSS z-index and box-shadow clipping problem


image-with-li-zIndex-1

body {
  background-color: gray;
}

h1 {
  color: white;
  text-align: center;
}

nav {
  margin: 30px;
}

ul {
  list-style: none;
  display: flex;
  padding: 0;
  margin: 0;
}

li {
  flex-grow: 1;
  flex-basis: 0;
  padding: 0 15px;
  min-height: 150px;
  margin: 0 1px;
  transition: all 0.3s ease-out;
  background-color: white;
  /* adding z-index here makes shadow on the right side to dissapear */
  z-index: 1;
}

li:hover {
  box-shadow: 0px 0px 65px -26px rgba(0, 0, 0, 0.75);
  transform: scale(1.09);
  /* if using z-index on hover it has overlap at the end
    z-index: 1; */
}

nav>span {
  position: absolute;
  left: calc(50% - 50px / 2);
  background: white;
  width: 50px;
  margin: 0 auto;
  box-shadow: inset 0px 6px 5px 0px grey;
  height: 22px;
  transition: all 0.3s ease;
}

nav>span:hover {
  cursor: pointer;
  height: 28px;
  margin-bottom: -3px;
  box-shadow: inset 0px 3px 5px 0px grey;
}
<nav>
  <ul>
    <li>item1</li>
    <li>hover me <br/>check box shadow on right side is missing because of z-index:1</li>
    <li>i want this item to be over the tiny square always but also with box shadow on right side working</li>
    <li>item4</li>
    <li></li>
  </ul>
  <span>
    
  </span>
</nav>
<h1>
  Some fake text which must not move, hence the little square is positioned absolute
</h1>

<p>
  1. Try removing z-index from li <br/> 2. Try having z-index on li hover only
</p>

JS Fiddle link

What i'm trying to achieve is a hover effect of the middle square box with box-shadow working.

For some reason if I use z-index:1 for all the big boxes, the box shadow is clipped on the right side. (see image)

The reason why I added z-index:1 is so that the middle box stays on top of the tiny square below it, which itself is position: absolute.

The reason why the tiny box is positioned: absolute; is to not shift any text below itself when it grows on mouse over.

The constraints are :

  1. Make the tiny white box to always appear behind the big boxes with shadow.
  2. Make sure the shadow works correctly on both sides.
  3. Make sure when hovering over the tiny white box, and it grows in height, it doesn't shift any elements below itself.

Solution

  • Increase the z-index value on hover:

    li:hover {
        box-shadow: 0px 0px 65px -26px rgba(0, 0, 0, 0.75);
        transform: scale(1.09);
        z-index: 2;
    }