Learn how to Access and Use Data Attributes in CSS

Updated onbyAlan Morel
Learn how to Access and Use Data Attributes in CSS

Data attributes are a great way to store data on an element without having to resort to using a custom attribute.

Because the format of the attribute names are standardized with the data- prefix, they be a great way to store data that can be used by JavaScript or CSS.

In this post, we'll learn how we can use data attributes to store data that can be used by CSS.

How to add data attributes

First, let's learn how we can add data attributes.

We can add data attributes to any element by using the data- prefix followed by the name of the attribute.

HTML
<div data-name="John Doe"> My name is </div>

In the above example, we added a data attribute named name to the div element.

How to target and style data attributes

Now that we know how to add data attributes, let's learn how we can style them.

We can style data attributes simply by adding the attribute name after the data- prefix.

CSS
[data-name] { color: red; }

See it in action:

  • HTML
  • CSS

This is useful because now any element that has a data attribute named name will be styled.

How to access data attributes with CSS

We can also access the value of a data attribute using CSS.

This means we can render text on the page based on the value of a data attribute.

Let's look at an example of this:

HTML
<div data-name="John Doe"> My name is </div>
CSS
[data-name]::after { content: attr(data-name); }

Let's see it in action:

  • HTML
  • CSS

Notice how it renders John Doe after the text My name is, even though we didn't add it to the markup.

Conclusion

In this post, we learned how we can use data attributes to store data that can be used by CSS.

We learned how to add data attributes to elements, how to style them, and how to access their values using CSS.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.