CSS shadows under adjacent elements

This article was posted by Michał Dudak on 2014-07-05 in CSS

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.

(Visited 7,416 times, 15 visits today)


  1. Irvin Shen says:

    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!

    1. I’m glad I could help!

Leave a Reply

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