{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreibgawstadbphi27rswbbizsd76px6gdg7ohxhckzkeae47lyikm5q",
"uri": "at://did:plc:25rdn5elo5izoxrmtis34zuk/app.bsky.feed.post/3mpjldh7zw2t2"
},
"coverImage": {
"$type": "blob",
"ref": {
"$link": "bafkreibc46ri3baxcbo4iobqiizu5sx7fnl3xww2hyzf4ntfhdt55ffto4"
},
"mimeType": "image/webp",
"size": 415524
},
"path": "/hasansarwer/a-practical-css-variable-setup-for-lightdark-mode-without-theme-flash-2gbl",
"publishedAt": "2026-06-30T17:23:50.000Z",
"site": "https://dev.to",
"tags": [
"css",
"webdev",
"darkmode",
"frontend",
"@media"
],
"textContent": "Dark mode is easy to start.\n\nIt is harder to ship cleanly.\n\nMost implementations need to handle:\n\n * light mode\n * dark mode\n * system preference\n * stored user preference\n * a toggle button\n * no flash of the wrong theme on page load\n\n\n\nThat last one is the annoying part.\n\nYou save the user's choice in `localStorage`, but your app JavaScript usually runs after the browser has already started parsing HTML and CSS.\n\nSo the page may briefly render in the wrong theme before JavaScript applies the saved preference.\n\nThis article shows a practical setup using:\n\n * CSS variables\n * `data-theme` on `<html>`\n * `prefers-color-scheme`\n * `localStorage`\n * a tiny inline script in `<head>`\n\n\n\nNo framework required.\n\n## The goal\n\nI want components to use semantic variables like this:\n\n\n\n body {\n background: var(--color-background);\n color: var(--color-text);\n }\n\n .card {\n background: var(--color-surface);\n border: 1px solid var(--color-border);\n }\n\n .button {\n background: var(--color-primary);\n color: var(--color-on-primary);\n }\n\n\nThe component should not care whether the app is currently in light mode or dark mode.\n\nOnly the variable values should change.\n\n## Step 1: define light mode variables\n\nStart with light mode as the default.\n\n\n\n :root,\n :root[data-theme=\"light\"] {\n color-scheme: light;\n\n --color-background: #ffffff;\n --color-surface: #f8fafc;\n --color-text: #0f172a;\n --color-muted: #64748b;\n --color-border: #e2e8f0;\n\n --color-primary: #2563eb;\n --color-on-primary: #ffffff;\n }\n\n\nThis means that if nothing else happens, the site renders in light mode.\n\nThat is a safe default.\n\nNotice that I also include:\n\n\n\n :root[data-theme=\"light\"]\n\n\nThis makes the explicit light mode clear and predictable.\n\n## Step 2: add explicit dark mode\n\nNow add dark mode using `data-theme=\"dark\"` on the root element.\n\n\n\n :root[data-theme=\"dark\"] {\n color-scheme: dark;\n\n --color-background: #020617;\n --color-surface: #0f172a;\n --color-text: #f8fafc;\n --color-muted: #94a3b8;\n --color-border: #1e293b;\n\n --color-primary: #60a5fa;\n --color-on-primary: #020617;\n }\n\n\nWhen this attribute exists:\n\n\n\n <html data-theme=\"dark\">\n\n\nThe dark variables override the light variables.\n\nYour component CSS does not change.\n\n## Step 3: support system preference\n\nSome users prefer dark mode at the OS level.\n\nYou can respect that with `prefers-color-scheme`.\n\n\n\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n color-scheme: dark;\n\n --color-background: #020617;\n --color-surface: #0f172a;\n --color-text: #f8fafc;\n --color-muted: #94a3b8;\n --color-border: #1e293b;\n\n --color-primary: #60a5fa;\n --color-on-primary: #020617;\n }\n }\n\n\nThe important part is this selector:\n\n\n\n :root:not([data-theme=\"light\"])\n\n\nIt means:\n\n> Use system dark mode unless the user explicitly selected light mode.\n\nSo the behavior becomes:\n\nSituation | Result\n---|---\nNo saved choice + OS light | light\nNo saved choice + OS dark | dark\nSaved `light` | light\nSaved `dark` | dark\n\n## Step 4: Prevent the wrong theme from flashing\n\nThis is the critical piece.\n\nAdd a small inline script in `<head>` before your theme CSS.\n\n\n\n <script>\n (function () {\n try {\n var storedTheme = localStorage.getItem('theme');\n\n if (storedTheme === 'light' || storedTheme === 'dark') {\n document.documentElement.setAttribute('data-theme', storedTheme);\n }\n } catch (_) {}\n })();\n </script>\n\n\nDo not run this script after the page loads.\n\nAvoid this:\n\n\n\n <script defer src=\"/theme.js\"></script>\n\n\nAvoid this:\n\n\n\n document.addEventListener('DOMContentLoaded', function () {\n // set theme here\n });\n\n\nThe script should run immediately while the browser is still parsing the `<head>`.\n\nWhy?\n\nBecause the browser reads the document from top to bottom.\n\nIf this script sets `data-theme=\"dark\"` before the CSS is applied, the correct variables are active before the first paint.\n\nThat prevents the wrong theme from flashing.\n\n## Recommended HTML structure\n\nPut the inline script before the CSS.\n\n\n\n <!doctype html>\n <html lang=\"en\">\n <head>\n <script>\n (function () {\n try {\n var storedTheme = localStorage.getItem('theme');\n\n if (storedTheme === 'light' || storedTheme === 'dark') {\n document.documentElement.setAttribute('data-theme', storedTheme);\n }\n } catch (_) {}\n })();\n </script>\n\n <style>\n :root,\n :root[data-theme=\"light\"] {\n color-scheme: light;\n\n --color-background: #ffffff;\n --color-surface: #f8fafc;\n --color-text: #0f172a;\n --color-muted: #64748b;\n --color-border: #e2e8f0;\n\n --color-primary: #2563eb;\n --color-on-primary: #ffffff;\n }\n\n :root[data-theme=\"dark\"] {\n color-scheme: dark;\n\n --color-background: #020617;\n --color-surface: #0f172a;\n --color-text: #f8fafc;\n --color-muted: #94a3b8;\n --color-border: #1e293b;\n\n --color-primary: #60a5fa;\n --color-on-primary: #020617;\n }\n\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n color-scheme: dark;\n\n --color-background: #020617;\n --color-surface: #0f172a;\n --color-text: #f8fafc;\n --color-muted: #94a3b8;\n --color-border: #1e293b;\n\n --color-primary: #60a5fa;\n --color-on-primary: #020617;\n }\n }\n </style>\n </head>\n\n <body>\n <button id=\"theme-toggle\" type=\"button\">\n Toggle theme\n </button>\n </body>\n </html>\n\n\nThe order matters:\n\n\n\n 1. Inline script reads saved preference\n 2. Script sets data-theme on <html>\n 3. CSS variables are applied\n 4. The browser paints the page\n\n\nIf the order is reversed, the wrong theme can appear briefly.\n\n## Step 5: Add the toggle function\n\nNow add a simple toggle.\n\n\n\n function toggleTheme() {\n var html = document.documentElement;\n var currentTheme = html.getAttribute('data-theme');\n\n var nextTheme = currentTheme === 'dark' ? 'light' : 'dark';\n\n html.setAttribute('data-theme', nextTheme);\n localStorage.setItem('theme', nextTheme);\n }\n\n document\n .getElementById('theme-toggle')\n ?.addEventListener('click', toggleTheme);\n\n\nNow, clicking the button switches between:\n\n\n\n <html data-theme=\"light\">\n\n\nand:\n\n\n\n <html data-theme=\"dark\">\n\n\nThe variables update instantly.\n\nNo component-specific class changes are needed.\n\n## Step 6: Add system mode\n\nA good theme switcher often has three options:\n\n * light\n * dark\n * system\n\n\n\nFor system mode, remove the attribute and clear `localStorage`.\n\n\n\n function resetToSystemTheme() {\n document.documentElement.removeAttribute('data-theme');\n localStorage.removeItem('theme');\n }\n\n\nNow the media query controls the theme again:\n\n\n\n @media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n /* dark variables */\n }\n }\n\n\nThis gives users a proper system preference option.\n\n## Why `color-scheme` matters\n\nThis line is easy to forget:\n\n\n\n color-scheme: light;\n\n\nand:\n\n\n\n color-scheme: dark;\n\n\nIt tells the browser which color scheme your page supports.\n\nThat can affect built-in UI such as:\n\n * form controls\n * scrollbars\n * default input styling\n * browser-rendered UI pieces\n\n\n\nSo your page does not only change your custom CSS variables. Native browser UI also gets a better matching appearance.\n\n## Component CSS stays simple\n\nOnce the variables are defined, component CSS becomes boring.\n\nThat is good.\n\n\n\n body {\n margin: 0;\n background: var(--color-background);\n color: var(--color-text);\n font-family: system-ui, sans-serif;\n }\n\n .card {\n background: var(--color-surface);\n border: 1px solid var(--color-border);\n border-radius: 12px;\n padding: 1rem;\n }\n\n .card-muted {\n color: var(--color-muted);\n }\n\n .button {\n background: var(--color-primary);\n color: var(--color-on-primary);\n border: 0;\n border-radius: 8px;\n padding: 0.625rem 1rem;\n cursor: pointer;\n }\n\n .button:hover {\n filter: brightness(0.95);\n }\n\n\nThere is no separate `.dark .button` rule.\n\nThe variables handle the mode.\n\n## Why semantic variables are better than color names\n\nYou could name your variables like this:\n\n\n\n --blue-600: #2563eb;\n --slate-950: #020617;\n --white: #ffffff;\n\n\nBut that becomes awkward in dark mode.\n\nFor example:\n\n\n\n .button {\n background: var(--blue-600);\n }\n\n\nShould `--blue-600` become lighter in dark mode?\n\nShould it stay the same?\n\nWhat happens if the primary color is no longer blue?\n\nSemantic names are more flexible:\n\n\n\n --color-background\n --color-surface\n --color-text\n --color-muted\n --color-border\n --color-primary\n --color-on-primary\n\n\nThese describe purpose, not appearance.\n\nThat makes the component CSS more stable.\n\n## The limitation\n\nThis setup solves the theme switching structure.\n\nIt does not solve color design for you.\n\nYou still need to decide:\n\n * which light colors to use\n * which dark colors to use\n * whether text has enough contrast\n * what hover, pressed, focused, and disabled states should be\n * what color should go on top of primary buttons\n * how semantic colors like success, warning, danger, and info behave in both modes\n\n\n\nFor a small project, manually writing variables may be enough.\n\nFor a larger system, maintaining all values by hand can become repetitive.\n\n## Optional: generating the variables\n\nIf you already have a design-token source, you can generate the CSS instead of writing it manually.\n\nThe output can still use the same structure:\n\n\n\n :root,\n :root[data-theme=\"light\"] {\n --color-background: ...;\n --color-text: ...;\n }\n\n :root[data-theme=\"dark\"] {\n --color-background: ...;\n --color-text: ...;\n }\n\n\nThe browser does not care whether the variables were handwritten or generated.\n\nThe important part is the contract:\n\n\n\n background: var(--color-background);\n color: var(--color-text);\n\n\nThe component uses meaning.\n\nThe theme supplies values.\n\n## The bottom line\n\nA reliable light/dark setup does not need to be complicated.\n\nThe key pieces are:\n\n\n\n CSS variables for tokens\n data-theme on <html>\n prefers-color-scheme for system fallback\n localStorage for user preference\n inline script in <head> to avoid theme flash\n\n\nThe most important rule is:\n\n> Set the saved theme before the CSS is applied.\n\nAfter that, your components can stay clean:\n\n\n\n background: var(--color-background);\n color: var(--color-text);\n\n\nThe values change between light and dark mode.\n\nThe component contract stays the same.",
"title": "A Practical CSS Variable Setup for Light/Dark Mode Without Theme Flash"
}