Subscribe

Working with data attributes in CSS

✍️

Did you know you could style data-attributes in CSS?

8 Dec, 2022 · 2 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.

See the Pen Untitled by Chris Bongers (@rebelchris) on 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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Modifying an SVG path with CSS

10 Dec, 2022 · 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 · 2 min read

Animate an SVG path with CSS

Join 2097 devs and subscribe to my newsletter