惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
N
Netflix TechBlog - Medium
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
博客园 - 【当耐特】
B
Blog
Stack Overflow Blog
Stack Overflow Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
博客园 - 司徒正美
博客园 - 叶小钗
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Dark Mode in 5 Minutes with salt-theme-gen (No Flash, Zer...
Hasan Sarwer · 2026-06-18 · via DEV Community
Cover image for Dark Mode in 5 Minutes with salt-theme-gen (No Flash, Zero Extra Dependencies)

Hasan Sarwer

The flash of wrong theme on page load is one of the most annoying unsolved problems in web development. You store the user's preference in localStorage, but JavaScript runs after the HTML and CSS, so there's a brief moment where the page renders in the wrong theme.

This article shows the complete pattern: generate both themes, inject CSS variables, and prevent the flash with a synchronous inline script. The whole setup takes under 5 minutes.

Generate both themes in one call

import { generateTheme } from 'salt-theme-gen';

const theme = generateTheme({ preset: 'ocean' });
// theme.light — all light mode tokens
// theme.dark  — all dark mode tokens

theme.light and theme.dark are both GeneratedThemeMode objects — same shape, different values. No separate calls, no configuration.

Build the CSS

Convert both modes to CSS custom properties:

function kebab(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase();
}

function modeToVars(mode: GeneratedThemeMode): string {
  const lines: string[] = [];

  for (const [k, v] of Object.entries(mode.colors))
    lines.push(`  --color-${kebab(k)}: ${v};`);
  for (const [k, v] of Object.entries(mode.surfaceElevation))
    lines.push(`  --surface-${k}: ${v};`);
  for (const [k, v] of Object.entries(mode.spacing))
    lines.push(`  --space-${k}: ${v}px;`);
  for (const [k, v] of Object.entries(mode.radius))
    lines.push(`  --radius-${k}: ${v}px;`);
  for (const [k, v] of Object.entries(mode.fontSizes))
    lines.push(`  --text-${k}: ${v}px;`);
  for (const [intent, states] of Object.entries(mode.states))
    for (const [state, val] of Object.entries(states as Record<string, string>))
      lines.push(`  --state-${intent}-${state}: ${val};`);

  return lines.join('\n');
}

export const themeCSS = `
:root {
${modeToVars(theme.light)}
}

:root[data-theme="dark"] {
${modeToVars(theme.dark)}
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
${modeToVars(theme.dark).split('\n').map(l => '  ' + l).join('\n')}
  }
}
`;

The three blocks in order:

  1. :root {} — light mode default, always applies
  2. :root[data-theme="dark"] {} — explicit dark, overrides when user toggled
  3. @media (prefers-color-scheme: dark) — OS dark preference as fallback when no stored choice

Inject it into <head>

This goes in your HTML <head> before any component styles:

<style>
  /* paste themeCSS content here */
</style>

Or dynamically (React/Next.js):

<style dangerouslySetInnerHTML={{ __html: themeCSS }} />

Astro:

<Fragment set:html={`<style>${themeCSS}</style>`} />

The flash-prevention script

This is the critical piece. It must run synchronously — no defer, no async, no DOMContentLoaded. Put it in <head> before the stylesheet:

<script>
  (function () {
    var stored = localStorage.getItem('theme');
    if (stored) {
      document.documentElement.setAttribute('data-theme', stored);
    }
  })();
</script>

Why it works: The browser processes <head> top to bottom before rendering. This tiny script runs, reads the stored preference, sets data-theme on <html>, and then the CSS (which comes after) applies the correct :root[data-theme="dark"] rules. By the time the first pixel is painted, the right theme is already active.

Toggle function

function toggleTheme() {
  const html = document.documentElement;
  const current = html.getAttribute('data-theme');
  const next = current === 'dark' ? 'light' : 'dark';
  html.setAttribute('data-theme', next);
  localStorage.setItem('theme', next);
}

Wire it to a button:

document.getElementById('theme-toggle')
  .addEventListener('click', toggleTheme);

Use tokens in CSS

body {
  background-color: var(--color-background);
  color:            var(--color-text);
  font-size:        var(--text-md);
}

.card {
  background:    var(--surface-card);
  border:        1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding:       var(--space-xl);
}

.btn-primary {
  background: var(--color-primary);
  color:      var(--color-on-primary);
}

.btn-primary:hover {
  background: var(--state-primary-hover);
}

When data-theme="dark" is set on <html>, all CSS variables update instantly — no JavaScript re-rendering, no class toggling on individual components.

OS preference + stored preference

The three-rule CSS handles both cases:

  • User has never toggled: @media (prefers-color-scheme: dark) matches their OS setting
  • User toggled manually: [data-theme="dark"] or [data-theme="light"] overrides the media query
  • User toggles back to match OS: clear localStorage and remove the attribute
function resetToSystem() {
  document.documentElement.removeAttribute('data-theme');
  localStorage.removeItem('theme');
}

Complete setup summary

1. npm install salt-theme-gen
2. generateTheme({ preset: 'ocean' })
3. Convert to CSS with modeToVars()
4. Inject into <head>
5. Add synchronous <script> before the <style> for flash prevention
6. Wire toggleTheme() to a button

Total time: under 5 minutes. Total JavaScript for the dark mode toggle: 3 lines.

Previous article: Introducing salt-theme-gen — Generate a Complete Design System from One Color

Full documentation: learn.esalt.net/salt-theme-gen


Part of the **salt-theme-gen — Design Tokens for Every Framework* series · Article 2 of 24*