Codementor Events

Pseudoelements don't really work with inline elements... or do they?

Published Dec 13, 2018

The title sounds like an obvious and well-known CSS fact, but I have seen experienced developers struggling with this topic, advising me to create overlays on images with pseudoelements. I was confident that pseudoelements do not work with inline elements , but then I played with the code, and it turned out, that statement is not entirely true. Let's see what is going on.

Pen

In pen above, you can see that after pseudoelement was added to img, input and div. But it only works with div element. Although after is visible in the inspector for both input and img element, it doesn't show on the screen. We can't see it nor select it.

Developer tools markup

Developer tools style

But what if we set the display property to block for input and img elements?

Pen

The pseudoelement after still did not show up. Let's look at more what-ifs. What if we add after to a span element, which is an inline element by default?

pen

Finally, the after pseudo-element is rendered. Can we say that it doesn't make a difference if we set the display property to block or inline? Let's play with some other elements to find an answer. Feel free to change the display property for every element.

pen

It looks like that only textarea, br and select can't handle pseudoelements. Changing the value of the display property did not make a difference.

Let's look now at the table and all its children elements. How are they going to render after pseudoelement?

pen

The after pseudoelement was rendered for all elements in the table: <table>, <thead>, <tbody>, <tr>, <th>, <td>. Those elements have various values of the display property: table-row, table-cell, table-header and others.

What we can conclude now is that display property of the element that contains pseudoelement does not affect the appearance of the after pseudoelement. What matters is to which element are we adding the after or before pseudoelement. Whether the after is going to appear or not depends on the HTML element itself, not its CSS properties. In other words, HTML elements have built-in preferences for displaying pseudoelements.

We can also say that all block level elements can always have pseudoelements, but some inline or inline-block elements, like <img> or <textarea>, may not render such pseudoelements.

Discover and read more posts from Antonija Šimić
get started
post commentsBe the first to share your opinion
HarshaL
5 years ago

Wow did not know that ! :)

Show more replies