Skip to main content

Command Palette

Search for a command to run...

Working with data attributes in CSS

Updated
1 min read
Working with data attributes in CSS
C

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.

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

M

Thank you so much given such a piece of valuable information about CSS. it's really helpful tips for me! I appreciate the author of this post sharing something special. I am super excited to share that I have found Graphicly!

Graphicly is an all-in-one plugin for graphics management, image cropping, and image optimization. Graphicly lets you easily download and use images from the web,

whether you are on a website or on your WordPress site. With our powerful API, you can create customized libraries of images that integrate seamlessly into your theme’s header.

You can also upload and store your own images directly within the plugin—so there’s less work to do when it comes to finding specific visual assets, images/videos that are relevant and needed by your website users.

as a result of reading this post. I'm getting to save your profile in my favorite list. 🥰

More from this blog

D

Daily Dev Tips

887 posts

Looking to get into development? As a full-stack developer I guide you on this journey and give you bite sized tips every single day 👊