Why don't the `img`, `iframe`, and `canvas` elements accept any pseudo-elements?

NicolasBrondinBernard

Author
@NicolasBrondinBernard

Some elements are incompatible with pseudo-elements, because they are themselves "replaced elements". Let's find out together what this means!

Article published on 29/01/2024, last updated on 10/08/2026

If you've ever tried adding pseudo-elements (::before and ::after) to tags such as img, iframe or even canvas, you've probably noticed that they don't appear...

So one might think that for an image, this is normal, given that it's a self-closing tag.

But that's not where the problem comes from!

And when we look at the case of an iframe for example, the behavior is even stranger: the pseudo-element is there, it exists in the DOM tree, but there's no way to make it display anything...

The reason

This "problem" is neither a bug nor a choice made by web browsers, but is in fact precisely described in the CSS specification!

Quite simply because these three tags are what is called "replaced elements"

Indeed, their content is replaced by an "external resource" to the original web page:

  • An image for <img>
  • Another web document for <iframe>
  • A pixel array for <canvas>

This means that their content is not taken into account in the CSS rendering model.

The element itself can of course be styled, but the style of the children (pseudo or not) is ignored.

The part of the specification about replaced elements: https://www.w3.org/TR/CSS21/conform.html#replaced-element

That's why the ::before and ::after pseudo-elements, even when added to the DOM, are never displayed, because they're ignored!

The solution

Unfortunately there's no magic solution, it's a constraint of browsers and the CSS specification...

The only viable solution is obviously to add a container around the original element, and add pseudo-elements to the container, in order to finally make them appear!


Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet