Dynamic CSS pseudo-element with data-attributes
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.
- create a regular button:
2. add before
attribute that will paint an arrow before the 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!
- add the needed content into the HTML tag as
data-attribute
(this can be changed dynamically by JavaScript):
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):
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:
And the CSS section stays the same.