There is a new feature I am working on at work that necessitates me to add a rotated element behind an image. I could easily just add another div to the DOM, but I wanted to do it with a CSS pseudo element to cut down on markup. Ideally, I would just add a class via JavaScript if a certain condition was met, and my special case would be “turned on.”
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 div
s 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 button
, textarea
, and 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 img
tag!
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!
References
StackOverflow: CSS :after not adding content to certain elements
W3C: Generated content, automatic numbering, and lists