Dynamic CSS pseudo-element with data-attributes

adi carmel
2 min readNov 9, 2019

--

Photo by Dan Meyers on Unsplash

If you want to keep your HTML content clean and nice, it’s a common practice to use before and after attributes to add extra content, or to design it.

A classic usage example for is when you want to add an arrow before the button text.

  1. create a regular button:

2. add before attribute that will paint an arrow before the button text:

Using “Before” property to add arrow before button text
Using “Before” property to add arrow before button text

As you can see I added an arrow with borders before the button text without changing the button markup and without duplicate styles between buttons.

But what if your “before” content is dynamic?

Well, luckily we can change CSS content property with HTML data attributes!

  1. add the needed content into the HTML tag as data-attribute (this can be changed dynamically by JavaScript):
adding the dynamic content as “data-attribute”

2. change the content property on the CSS to use attr value with the same name as you wrote on the HTML (data-before in this example):

Using “data-attribute” to show dynamic content before button text
Using “data-attribute” to show dynamic content before the button text

And that’s it — super simple way to add a dynamic content into CSS pseudo-element!

JSX implementation

If you are using JSX you can implement the HTML side like that:

JSX implementation

And the CSS section stays the same.

--

--