Last update:

CSS shadows under adjacent elements

The problem

Having several elements close to each other and applying a box shadow on them may cause the shadow from an element to render on top of the previous element, like this:

See the Pen Overlapping shadows

This is caused by the fact that the shadow of an element is tied to it and nothing can be inserted between a box and its shadow. This, of course, may be perfectly fine in some cases, but let’s focus on changing this behavior – we would like to have shadows under all element.

Shadows under elements

To overcome this, we’ll have to somehow separate the element and its shadow. Fortunately, CSS makes it possible with pseudoelements. We’ll render the shadow in a pseudoelement (could be either before or after, it doesn’t matter) and assign a negative z-index to it. It is important that the element itself does not have a z-index property (or has it set to auto):

The :before pseudoelement is a box that has the same size as the original element, but thanks to the lower z-index, it is rendered below other elements.

See the Pen Fixed overlapping shadows1

“All right, but why can’t we set any z-index to the original element?” – you may ask. The reason is that setting the z-index creates a new local static context and elements from these contexts can’t be interwoven.

Why would I need it?

For example, to create complex interfaces with drop shadows:

See the Pen Complex layout1

Throw in some border radius to create even more crazy stuff:

See the Pen Large box vertices1

Browser support?

I tested it in IE >=9, latest Chrome and Firefox on Windows and I didn’t spot any problems. Older IEs don’t support box-shadow, so nope.


  1. Hey, I just wanted to let you know that you were a huge help! I was using some pseudo-material design with an interactive box, with multiple buttons, making up the bottom. Thanks to this post, I was able to fix the shadowing on it!

    Irvin Shen on 16 January 2018, 11:38 UTC Reply
    1. I’m glad I could help!

      Michał Dudak on 16 January 2018, 11:54 UTC Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Michał Dudak