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!

I’d love to know if any of these articles helped you.
Share what you’re building or ask me a question on Threads or somewhere else.

Instagram is a great place to see my final creative coding experiments, while the others are are great place to connect or see progress updates.

If my content has helped you, I’d never say no to donations to help me keep writing.

Here are some other things you might like


Author:

Date:

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.