CSS Data Attribute Selector — Using Custom data-* Attributes

Learn how to use CSS selectors to target elements with custom data-* attributes. Covers data-driven styling patterns used in modern JavaScript frameworks and component libraries.

Attribute Selectors

Detailed Explanation

Selecting Data Attributes in CSS

Custom data-* attributes provide a clean way to attach metadata to HTML elements. CSS can target these attributes using the standard attribute selector syntax.

Basic Usage

<button data-variant="primary">Save</button>
<button data-variant="secondary">Cancel</button>
<div data-loading="true">Loading...</div>
[data-variant="primary"] {
  background: blue;
  color: white;
}

[data-variant="secondary"] {
  background: gray;
  color: white;
}

[data-loading="true"] {
  opacity: 0.5;
  pointer-events: none;
}

Pattern: State-Based Styling

Data attributes are ideal for representing component states:

/* Accordion panel visibility */
[data-expanded="false"] { display: none; }
[data-expanded="true"] { display: block; }

/* Toast notification types */
[data-toast="success"] { border-color: green; }
[data-toast="error"] { border-color: red; }
[data-toast="warning"] { border-color: orange; }

Pattern: Responsive Variants

/* Grid column spans */
[data-cols="1"] { grid-column: span 1; }
[data-cols="2"] { grid-column: span 2; }
[data-cols="3"] { grid-column: span 3; }

Advantages Over Classes

  • Semantic meaning is clearer (data-state="active" vs .is-active)
  • Values can be set dynamically from JavaScript with dataset
  • No need to add/remove classes — just update the attribute value
  • Better separation between styling hooks and behavioral hooks

Framework Integration

React, Vue, and Svelte commonly use data attributes for component variants. Libraries like Radix UI and Headless UI expose data-state, data-open, and similar attributes for styling.

Use Case

Data attribute selectors are the foundation of modern component styling in frameworks like Radix UI, Headless UI, and custom design systems. They provide a clean API for component variants (data-size, data-variant), state management (data-state, data-active), and dynamic theming (data-theme). React developers frequently use them to avoid className string manipulation.

Try It — CSS Selector Tester

Open full tool