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
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):
box-shadow: -5px 5px 20px 5px #000;
: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
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.