Pseudoelements don't really work with inline elements... or do they?
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.
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.
But what if we set the display
property to block
for input
and img
elements?
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?
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.
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?
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.
Wow did not know that ! :)