Skip to content

Dark Mode ​

getInitialTheme() first checks the value saved in localStorage, and if there is none, reads the system setting through the prefers-color-scheme: dark media query.

The selected theme is reflected in document.documentElement.dataset.theme, and the [data-theme="dark"] selector in base.css overrides CSS variables of the same names with different values, so all the colors change at once.

css
:root {
  --color-bg: #f8fafc;
  --color-text: #182230;
}

[data-theme="dark"] {
  --color-bg: #0f172a;
  --color-text: #f8fafc;
}

Each time the theme is toggled, the value is saved with localStorage.setItem('theme', ...), so it persists after a refresh.

Why localStorage and Not Cookies? ​

There are several ways to store values in the browser: cookies, localStorage, sessionStorage and more. localStorage is a good fit for the theme value for the following reasons.

CookielocalStoragesessionStorage
Sent to the server automaticallySent with every requestNot sentNot sent
LifetimeUntil the expiration timeUntil you delete it yourselfUntil the tab is closed
CapacityAbout 4KBUsually around 5MBUsually around 5MB
Fit for this projectWasteful, since the server doesn't need to know the themeGood fit, since it persists after refreshes and return visitsPoor fit, since it disappears when the tab is closed

The theme is a value only the browser drawing the screen needs to know, so there is no reason to put it in a cookie that travels to the server with every request. On the other hand, if the server has to build dark mode HTML from the start (server-side rendering), storing it in a cookie is the right choice. Differences between storage types are covered in detail in the Cookies and Sessions article.

The Screen Flashing Briefly on Refresh ​

If you refresh with dark mode on, sometimes a bright screen shows for a split second before it turns dark. This is because of the order in which the browser draws the screen.

Parse HTML → Apply CSS → Draw first screen (light theme) → Run main.js → data-theme="dark" → Redraw
                          ↑ this moment is the flash

If the JS that decides the theme runs after the first screen is drawn, the default (light) colors are visible in between. The fix is to run a short piece of code that decides the theme inside <head>, before the CSS is applied.

html
<head>
  <script>
    const saved = localStorage.getItem('theme');
    const dark = saved ? saved === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
    document.documentElement.dataset.theme = dark ? 'dark' : 'light';
  </script>
  <link rel="stylesheet" href="base.css" />
</head>

VitePress, which this site (1mo.dev) is built with, prevents the flash the same way by putting a small script in <head>. The order in which the browser reads HTML and draws the screen is covered in detail in the How Browsers Work article.

Summary ​

StepWhat it does
1Use the theme saved in localStorage, if any
2Otherwise, follow the OS setting (prefers-color-scheme)
3Change <html data-theme> to swap out the CSS variables all at once
4Save to localStorage every time the button is pressed
  • The theme is a value the server doesn't need to know, so localStorage fits better than cookies
  • To get rid of the flash on refresh, run the theme-deciding code in <head> before the screen is drawn

Source: Codyssey-B1/B1-1