×

Data attribute in HTML & CSS

Introduction

Modern web development often requires attaching extra information to HTML elements—information that isn’t necessarily visible to users but is useful for styling, interaction, or logic. This is where HTML data-* attributes come in.

This article explains:


What are data-* Attributes?

data-* attributes are custom attributes introduced in HTML5 that allow you to store extra data directly on HTML elements.

Basic Syntax

<div data-role="admin" data-user-id="123"></div>

Rules:


Why Do data-* Attributes Exist?

Before HTML5, developers often:

data-* attributes solve this by providing: ✅ Valid HTML ✅ Semantic meaning ✅ Easy access from JavaScript ✅ Usable in CSS selectors


Using data-* Attributes in HTML

They are commonly used to describe:

<button data-action="delete" data-id="42"> Delete </button>

Using data-* Attributes in JavaScript

JavaScript provides the dataset API for easy access.

Example

<button id="btn" data-action="delete" data-id="42">Delete</button>
const btn = document.getElementById("btn"); console.log(btn.dataset.action); // "delete" console.log(btn.dataset.id); // "42"

Important Notes

const id = Number(btn.dataset.id);

Using data-* Attributes in CSS

You can style elements using attribute selectors.

Example

<div data-theme="dark">Dark Theme</div> <div data-theme="light">Light Theme</div>
[data-theme="dark"] { background: #111; color: #fff; } [data-theme="light"] { background: #fff; color: #000; }

This is useful for:


❓ Is data-* Mandatory for CSS?

No.

CSS does not require the data- prefix.

This works perfectly in CSS:

<div user-type="admin">Admin</div>
[user-type="admin"] { color: red; }

⚠️ But This Is Important

Although CSS allows any attribute, HTML standards do not.

Valid HTML

data-user-type="admin"

Invalid / Non-standard HTML

user-type="admin"

➡️ Browsers may allow it, but:


Best Practice Recommendation

Use CaseRecommended Approach
JavaScript + CSSdata-* attributes
CSS only (quick styling)data-* (still preferred)
Temporary JS logicJS variables
Styling onlyClasses
Meaningful element metadatadata-*

Use data-* attributes whenever the value represents data, not style.


When NOT to Use data-*

Avoid data-* when:

❌ Bad Example

<div data-margin="20"></div>

Use CSS instead:

.box { margin: 20px; }

Real-World Example: Toggle Theme

<body data-theme="dark">
body[data-theme="dark"] { background: #121212; color: #fff; } body[data-theme="light"] { background: #ffffff; color: #000; }
document.body.dataset.theme = "light";

✔ Clean ✔ Semantic ✔ Maintainable


Key Takeaways