DEV Community

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

Posted on

1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more