Inner shadows on Image Elements
I recently found myself wanting to style an image component with an inner shadow and hit a snag. It simply wouldn’t appear.
Turns out that images cover up inner shadows, so let’s dive into how to get around it.
The problem
The problem, I quickly found, was that when you set the box-shadow CSS property to inset, the shadow will appear above the background of that element, but below it’s content.
Since an image within a div counts as the divs content, the image would always cover a shadow set on the div, however, even if you apply the box-shadow directly to the image, the image still covers its own inset shadow.
Below is a Codepen example that shows the problem.
Image on the left:
For this image, I’ve set an inset box-shadow on the div container, and thus the contents (the image) covers it up.
Image on the right:
For this image, I’ve applied the inset box-shadow on the image directly, but even here, the image still covers it up.
Background image solution
An easy solution around this is to apply the image as a background-image to the div. This will mean it’s no longer part of the div’s content and therefore sits underneath the inset shadow.
If you can’t do that, though, keep reading.
Another solution
The solution I found was to apply the inner shadow via an after pseudo-element. As a Pseudo element to the div (The images container), the after becomes part of the content just like the image, and, as an after, its stacking order is last—which means it’s on top.
Note
Depending on your browser, this solution may not work on the right image as, according to this answer on Stack Overflow, pseudo elements might not be that well implemented for img tags – Though that thread is pretty old.
That’s it!
Thanks…
I also dissect and speculate on design and development.
Digging into subtle details and implications, and exploring broad perspectives and potential paradigm shifts.
Check out my conceptual articles on Substack or find my latest below.
You can also find me on Threads, Bluesky, Mastodon, or X for more diverse posts about ongoing projects.
Leave a Reply