DEV Community

Cover image for Beginner's guide to data-attributes in CSS
Arindam Chowdhury
Arindam Chowdhury

Posted on

Beginner's guide to data-attributes in CSS

What are data-attributes?

They are custom HTML attributes, that you can use on any HTML elements. You just need to prefix those custom attributes with data-.

It's recommended not to make your own attributes, i.e., creating attributes which are not prefixed with data-.

Syntax

You can use anything after data-. And one HTML element can have multiple data attributes.

<div data-category='cars' data-type='luxury'> 
    Audi 
</div>
<div data-category='laptop'>
    Lenovo
</div>
Enter fullscreen mode Exit fullscreen mode

data-attribute-meme

Use Cases

Javascript

Suppose you want to add custom icons, based on the data-category.

div elements

  • You can access data-attributes via getAttribute(attribute-name)
const data = document.querySelectorAll("[data-category]");
data.forEach((item) => {
  console.log(item.getAttribute("data-category")) 
  // cars or laptop will be the output  
  // Add icons based on cars or laptop
})

Enter fullscreen mode Exit fullscreen mode
  • You can also access them via dataset property.

If you console.log(item.dataset), you'll see all the data-attributes for that HTML element, in an object.

const data = document.querySelectorAll("[data-category]");
data.forEach((item) => {
  console.log(item.dataset.category) 
  // cars or laptop will be the output   
  // Add icons based on cars or laptop 
});
Enter fullscreen mode Exit fullscreen mode

After adding the required Javascript, this is how it looks

div-elements-with-icons

CSS

Now, if we want to add custom designs to the elements, based on the data-attributes, we can select them in CSS using the attribute-selector.

[data-category="cars"] {
  background:  #feffd4 ;
}
Enter fullscreen mode Exit fullscreen mode

After, adding the required CSS, this is how it looks

Further Readings:

How to use the DATA attribute with JavaScript, HTML and CSS

Mozilla Docs

CSS Tricks: A complete Guide to Data attributes

Top comments (0)