Explain Codes LogoExplain Codes Logo

Css values using HTML5 data attribute

html
responsive-design
css-custom-properties
data-attributes
Nikita BarsukovbyNikita Barsukov·Feb 4, 2025
TLDR

Leverage HTML5 data attributes in CSS with the attr() function for dynamic style adjustments. From simple changes to content:

div::before { content: attr(data-tooltip); /* Hey, I'm dynamic! */ color: blue; }
<div data-tooltip="Hover over me!"></div>

To calc() rocking with CSS Variables for changing sizes:

div { --dimension: attr(data-size px); /* So magic. Much flexible. */ width: calc(var(--dimension) * 1); height: calc(var(--dimension) * 1); }
<div data-size="100"></div>

Note: calc() multiplies by 1, magically converting string to a legit CSS unit. Abracadabra!

Plumbing the depths: Advanced usage and limitations

Though attr() opens a realm of possibilities for dynamic styles, it's still within experimental territory for properties other than content. Meaning, our magic wand may not work on all spells just yet.

Browser limitations: The Muggles of the wizarding world

attr() doesn't vibe well with properties like width or height in majority of browsers. So, for now, we resort to our trusty friend JavaScript to bridge the gap. Stay alert for browser update news, changes are brewing!

Polyfills: Expecto Patronum!

Waiting for native support? Polyfills such as cssattr.js might be your Patronus, combatting the fear of lack of attr() compatibility across different CSS properties. Fabrice Weinberg's workaround enables attr() even for setup moves like width and height.

JavaScript: The old Reliable

Often, JavaScript is invoked to read data attributes and apply them to CSS dynamically. Like a potion master concocts a brew, you can write a JavaScript loop recipe to create CSS rules for each data attribute, mastering the art of style modification.

Unleashing the power of data attributes

Hang tight while we explore the territories where CSS and JavaScript join forces with data attributes to cast some practical and dynamic styling spells.

JavaScript: The Dynamic Duo

JavaScript can be summoned to read data attributes and apply them as cascading styles:

document.querySelectorAll('[data-bgcolor]').forEach(function(el) { el.style.backgroundColor = el.getAttribute('data-bgcolor'); /* Colors everywhere! 🌈 */ });
<div data-bgcolor="#ffcc00"></div>

Dynamic stylesheets: The Marauder’s Map

Deploy a <style> element into the DOM with custom CSS rules based on data attributes:

let styleSheet = document.createElement('style'); document.head.appendChild(styleSheet); document.querySelectorAll('[data-dynamic]').forEach(function(el) { let dynamicValue = el.getAttribute('data-dynamic'); let className = "Mischief Managed!" + dynamicValue; el.classList.add(className); styleSheet.sheet.insertRule(`.${className} { /* Shhh...Secret CSS code */ }`, 0); });

Tackle specificity and cascade: Defense Against the Dark Arts

Dynamic styles can clash Voldemort-style with existing styles. Fear not! Increase specificity of your dynamically generated rules or use !important to ensure harmony.

Mastering CSS Custom Properties

CSS Custom Properties really shine when conjured with data attributes. Imagine a theme toggle switch:

<body data-theme="dark"> <!-- Welcome to the Dark Side --> </body>

Set up your CSS to reference these variables:

:root { --background-default: white; /* Pure as Snow White */ --background-dark: black; /* As black as Batman's cape */ --text-default: black; --text-dark: white; } body[data-theme="dark"] { --background: var(--background-dark); --text-color: var(--text-dark); } body { background: var(--background, var(--background-default)); color: var(--text-color, var(--text-default)); }

By simply flipping the data-theme attribute value, your website switches between Batman mode and Snow White mode effortlessly.