We have a lot of images on our site and make use of the
img tag heavily to load up our assets instead of using
divs and setting a background image. What I learned and didn’t realize about until today, is that image tags are something called “replaced elements.”
What is a replaced element?
A replaced element is something that has its appearance controlled by an external resource. So what does that mean? It could mean that its behavior and appearance is controlled by the browser itself. This is why other replaced elements like
input all look different depending on which browser you use because how those elements are displayed is up to the browser.
On these replaced elements, pseudo elements like :before and :after don’t work, and aren’t meant to work due to their inherent responsibility and purpose. This behavior is directly mentioned in the spec. Too bad I didn’t realize it until I had already spent a few days wondering why my style works on a
div but I couldn’t find it when I tried swapping it to an
Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
The workaround for to get my desired behavior is not difficult to achieve at all once you realize you can’t manipulate the
img tag directly. All you need to do is wrap your image (or other replace element) in a block element like a
div and then you can use the :before and :after pseudo elements to their full capacity.
I hope this information helps someone else out there who may not have known about this little piece of behavior in HTML!
LIKE THIS POST?
Sign up for updates and get fresh content delivered straight to your inbox.