Learn how to Access and Use Data Attributes in CSS
Table of Contents
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!
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications