Enhanced CSS attr() -- Read Any HTML Attribute as Any Type
The attr() function has existed in CSS for decades, but it only worked with the content property. That's finally changed. Enhanced attr() now works with any CSS property and can parse values as colours, lengths, numbers, and more. Chrome 133+ stable.
The New Syntax
/* Old: only worked with content */
.tooltip::after {
content: attr(data-tip);
}
/* New: works with ANY property */
.box {
width: attr(data-width type(<length>), 100px);
color: attr(data-color type(<color>), black);
opacity: attr(data-opacity type(<number>), 1);
}
Data Attributes as a Styling API
Here's the thing -- this turns HTML data attributes into a powerful styling API:
<div class="card" data-bg="#3b82f6" data-padding="2rem" data-radius="12px">
Dynamic styling from HTML
</div>
.card {
background: attr(data-bg type(<color>), #fff);
padding: attr(data-padding type(<length>), 1rem);
border-radius: attr(data-radius type(<length>), 4px);
}
Real-World Use: Dynamic Grid
<div class="grid" data-cols="3" data-gap="1.5rem">
...
</div>
.grid {
display: grid;
grid-template-columns: repeat(attr(data-cols type(<number>), 1), 1fr);
gap: attr(data-gap type(<length>), 1rem);
}
Browser Support
Chrome 133+ (stable). Chromium-only currently.
- Works with any CSS property, not just content
- Supports type parsing: color, length, number, percentage
- Fallback values for graceful degradation
- No JavaScript needed for data-driven styling
Happy coding!
If you want to go deeper and learn how to build real, production-ready CSS design systems step by step, check out my full course here: CSS Design Systems Course If you found this helpful, I'd love to connect! Follow me on Twitter/X @alexandersstudi or LinkedIn for more CSS and design system tips.