Does :before not work on img elements?
Your hunch is correct. The :before
and :after
pseudo-elements don't work on **<img>**
elements as they are viewed as replaced elements by browsers. But, here's a workaround. Create a <div>
wrapper and apply your :before
to it.
Yet, other alternative approaches can be, employing JavaScript/jQuery, or using different HTML elements.
Working with JavaScript/jQuery
Here is a method to circumvent the absence of :before
selector with <img>
using JavaScript/jQuery. This approach adds a <span>
after your targeted image:
This is a straightforward and effective way to append content right after an image.
Exploring HTML alternatives
Choosing <picture>
element
Surprisingly, the <picture>
element supports pseudo-elements and could be an alternative to <img>
tag.
You can directly apply the :before
or even :hover::after
pseudo-element to <picture>
to get started with your fancy overlay effects.
Using <div>
containers
Wrapping your <img>
with a <div>
container gives you more control over the position of add-on contents. This parent container envelops both the image and overlays, allowing ease in positioning.
Content property on pseudo-elements
Let your creativity flow with the **content**
property on a pseudo-element. It allows you to insert images and text, making it ideal for adding little icons or multimedia content.
Cross-browser compatibility
Overlay techniques
Let's create image overlays on hover by using :hover::after
, reducing the need for extra elements within the HTML structure.
Compatibility considerations
It's always the outdated browsers that throw a spanner in the works. So be wary when dealing with Internet Explorer 8/9. Cross-browser friendly methods are a go-to for wider compatibility.
Resources and practical examples
jQuery overlay example
Test your solution across varied browsers to ensure that your overlays act consistently across all of them.
Helpful external resources
Utilize trusted resources, such as MDN and CSS-Tricks, for implementation specifics including code snippets.
In-action visualizations
You can never underestimate the value of seeing things in action with demos like on jsFiddle. They provide practical examples of how your overlays behave in a real-world environment.
Older browser limitations
Take time to review the quirks that older browsers present. There may be limitations with certain techniques like "I'm just fake content".
Was this article helpful?