Working with data attributes in CSS

Working with data attributes in CSS


1 min read

We previously looked at using data attributes in JavaScript. These data attributes are a fantastic way to store little bits of information on an element without using custom attributes.

However, we can also use them to style some aspects with specific attribute sets.

CSS attributes in CSS

To paint a simple picture, let's create elements that hold a specific value like this.

<div data-rating="1">Rating</div>
<div data-rating="5">Rating</div>

As you can see, our rating is only set as the custom attribute.

Let's first look at how we can style this object, which is very easy by simply using its name.

[data-rating] {
  color: indigo;

With this, the rating text will be purple.

We can also make it more specific and add styling for particular values.

[data-rating='1'] {
  color: red;
[data-rating='5'] {
  color: indigo;

And to top it off, we can inject the value with CSS!

[data-rating]::after {
  content: attr(data-rating);

Which would result in the rating being added after our text.

You can play with these data attributes on the following CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter