How to layer box-shadows using z-index?

If you're using z-index, make sure the element has a defined position attribute or it won't work. Wherever you use z-index in your css, define the position of that element. (Absolute, relative, inherit...)


Try using inset box-shadow on list elements and when a selected element has class .current then remove the inset shadow from it.


Demo: http://codepen.io/anon/pen/vLgKC

Tip: Make sure position is explicitly set on elements with z-index e.g. relative etc, even if you're fine with the default, it has to be set.

For more info on z-index and stacking context and the priorities please see my answer here.

The above, combined with the inset for box-shadow

inset

If not specified (default), the shadow is assumed to be a drop shadow (as if the box were raised above the content). The presence of the inset keyword changes the shadow to one inside the frame (as if the content was depressed inside the box). Inset shadows are drawn inside the border (even transparent ones), above the background, but below content.

And a negative spread

spread-radius

This is a fourth value. Positive values will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink. If not specified, it will be 0 (the shadow will be the same size as the element).

(Both here)

Will give you the effect that you are looking for.

So you will need to change the place that the shadows are applied on elements.

So the final CSS:

   #b {
      background: orange;
      z-index: 2;
      position: relative;
    }
    
    #c {
      background: red;
      -webkit-box-shadow: inset 0 10px 10px -10px black;
      -moz-box-shadow: inset 0 10px 10px -10px black;
      box-shadow: inset 0 10px 10px -10px black;
      z-index: 1;
      position: relative;
    }
    
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
      z-index: 1;
      position: relative;
    }
    li {
      display: inline-block;
      padding: 2px 5px;
    }
    
    .current {
      background-color: orange;
      z-index: 3;
      position: relative;
    }
    
    #d {
      box-shadow: 0 0 10px black;
      z-index: 2;
    }
<div id="a">
  <div id="b">bbb</div>
  <div id="c">
    <ul>
      <li>a</li>
      <li class="current">b</li>
      <li>c</li>
      <li>d</li>
    </ul>
  </div>
</div>
<div id="d">dddd
</div>

Tags:

Css