Code Theme Switching in Tech Blogs Without Prism CSS Collisions
Dark/light code themes often break syntax colors because token selectors overlap. The safe strategy is scoped theme classes with variable-driven tokens.
Step 1: namespace code theme variables
.code-theme-light {
--code-bg: #f8fafc;
--code-fg: #0f172a;
}
.code-theme-dark {
--code-bg: #0b1220;
--code-fg: #e2e8f0;
}
Step 2: bind Prism token colors to your variables
pre[class*="language-"] {
background: var(--code-bg);
color: var(--code-fg);
}
Step 3: toggle theme class at article container only
article.classList.toggle('code-theme-dark', prefersDark)
Pitfall
Injecting second Prism stylesheet dynamically. Order-dependent overrides produce inconsistent token colors.
Verification
- Token colors stay readable in both themes.
- No global theme side effects on non-code elements.
- Theme toggle works on cached and uncached pages.