DEV Community

hannah 🐙
hannah 🐙

Posted on • Edited on

Adding pseudo-elements on input elements 🚫

Before you sink hours into trying to work out why that ::after pseudo-element isn't working on your text input, let me save you some time and tell you that you can't - without some extra work that is.

TLDR; Add the ::after to a sibling <span> element.

The reason being is that pseudo-elements are only supported on container elements.

W3C's specification states the following:

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

But what does that mean!?

Pseudo-elements are rendered in your code as child elements of parent elements.

This means that rendering an ::after selector on a button is fine, because it can be rendered as a child within a <button> component without a problem because it's a container element, as shown below.

Alt Text

However, the below code won't work, because <input> elements don't support children. It's not a container element, like <button> is.

Alt Text

If you're not well acquainted with <input> elements, here's an example of valid usage of an <input> element. Observe the fact that there's an immediate closing tag without any children within that element.

Alt Text

See the problem? An ::after pseudo-element can't render within an <input> because it's not a container element; it cannot support any children. So how do we get around this?

The solution is to apply an ::after pseudo-element on a sibling <span> element.

Alt Text

Here, we are adding an ::after selector when the <input> focus state is active. By targeting the focus state, we can append a pseudo-element to an empty adjacent <span> element and work around the <input>'s container issue.

Here's a codepen to demonstrate this.

I hope you found this useful! Follow me on the bird app @erhannah for more web dev shenanigans/virtual reality chat/dog pics. ✨

N.B: Yes, I know you could also get around this with jQuery. But it's 2020.


Hi! I'm Hannah. I'm a virtual reality developer, senior frontend developer, vrcalm cofounder helping dementia patients, and tech for good enthusiast. 🌎

Top comments (0)