Scoped Theme Variables with Data Attributes
What you'll learn: How to apply different themes to specific sections of your app using data-theme attributes and scoped CSS variables.
The Core Idea
Instead of forcing your entire app to use one theme at a time, you can create themed "zones" by applying data-theme attributes to specific subtrees. CSS variable selectors can then scope different values based on these attributes, allowing multiple themes to coexist on the same page.
How It Works
Think of it like painting different rooms in a house different colors—each room (subtree) has its own palette (theme), but they all exist in the same building (app).
In your CSS, define theme-specific variables under attribute selectors:
[data-theme="light"] {
--color-bg: white;
--color-text: black;
}
[data-theme="dark"] {
--color-bg: black;
--color-text: white;
}
In React, apply the attribute to the container whose children should use that theme:
function DualThemeLayout() {
return (
<div>
<section data-theme="light" style={{
background: 'var(--color-bg)',
color: 'var(--color-text)'
}}>
<h2>Light Section</h2>
<p>This area is always light.</p>
</section>
<section data-theme="dark" style={{
background: 'var(--color-bg)',
color: 'var(--color-text)'
}}>
<h2>Dark Section</h2>
<p>This area is always dark.</p>
</section>
</div>
);
}
All children inherit the scoped variables automatically through CSS cascade. You can dynamically change data-theme values just like any React prop.
Key Takeaway: Data attributes combined with CSS variables create powerful scoped theming that lets different parts of your app use different themes simultaneously, perfect for complex UIs with mixed-theme requirements.