🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Styling••By Komal Nakrani

Astro Dark Mode Toggle Without the Flash

Add Astro dark mode with no flash of the wrong theme: an inline head script, CSS variables, an accessible toggle, Tailwind support, and View Transitions fixes.

#Astro#Dark Mode#CSS#Styling#View Transitions

To add Astro dark mode without a flash, put a small <script is:inline> in the <head> that reads the saved preference (or prefers-color-scheme) and sets data-theme on <html> before the page paints. Style both themes with CSS variables keyed off that attribute, and let a toggle button update the attribute and localStorage. If you use View Transitions, reapply the theme on astro:before-swap.

The flash happens when the theme is decided too late: the page renders light, then JavaScript switches it to dark. Every step below exists to make the decision before the first paint.

Key Takeaways

  • The theme script must be inline and blocking in the <head>; a bundled <script> runs too late.
  • Store the theme on <html> as data-theme or a dark class, and drive colors with CSS variables.
  • Respect the operating system setting until the visitor picks a theme.
  • Set color-scheme so form controls and scrollbars match the theme.
  • With <ClientRouter />, copy the theme onto the incoming document in astro:before-swap.

Why Astro dark mode flashes

Astro renders HTML at build time, when it cannot know which theme a visitor prefers. The browser receives light-themed HTML, starts painting, and only later runs your module scripts, which are deferred by default. If those scripts flip the theme, the visitor sees a white frame first. That is the flash of incorrect theme, sometimes called FOUC.

The fix is to run a tiny piece of JavaScript synchronously while the browser parses the <head>. Parsing stops for a few microseconds, the attribute is set, and the first paint already uses the right colors. Astro’s is:inline directive is what makes this possible: it tells Astro not to bundle or defer the script, so it stays exactly where you put it.

Step 1: the inline theme script

Put this in the <head> of your base layout, above your stylesheets:

---
// src/layouts/BaseLayout.astro
import '../styles/global.css';
const { title } = Astro.props;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
    <script is:inline>
      (() => {
        let stored = null;
        try { stored = localStorage.getItem('theme'); } catch {}
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        const theme = stored === 'light' || stored === 'dark' ? stored : prefersDark ? 'dark' : 'light';
        document.documentElement.dataset.theme = theme;
      })();
    </script>
  </head>
  <body>
    <slot />
  </body>
</html>

A few details matter here. The try block protects against browsers that throw when storage is disabled. The value is validated, so a stale or tampered value falls back to the system preference. And the script is wrapped in a function so its variables do not leak into the global scope.

Because is:inline scripts are not processed, you cannot use TypeScript or imports inside them. Keep the script this small. If you need the theme logic in other places, duplicate the few lines rather than importing a module.

Step 2: CSS variables for both themes

Define your palette once as custom properties, then override it for dark mode:

/* src/styles/global.css */
:root {
  color-scheme: light;
  --bg: #ffffff;
  --surface: #f8fafc;
  --text: #0f172a;
  --muted: #475569;
  --border: #e2e8f0;
  --accent: #2563eb;
}

:root[data-theme='dark'] {
  color-scheme: dark;
  --bg: #0b1120;
  --surface: #111827;
  --text: #e5e7eb;
  --muted: #94a3b8;
  --border: #1f2937;
  --accent: #60a5fa;
}

body {
  background: var(--bg);
  color: var(--text);
}

color-scheme tells the browser to render native controls, scrollbars and the default page background in the matching theme. Without it, a dark page can still show a bright white scrollbar or light date picker.

Components then use the variables instead of fixed colors, which means a component never needs to know which theme is active:

---
// src/components/Card.astro
---
<div class="card"><slot /></div>

<style>
  .card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 0.75rem;
    padding: 1.25rem;
  }
</style>

Naming and organising these variables is a topic of its own, covered in design tokens with CSS variables in Astro.

Step 3: an accessible toggle button

The toggle only needs to flip the attribute, save the choice and update its own label. A regular bundled <script> is fine here, because it runs after the page has already painted with the right theme:

---
// src/components/ThemeToggle.astro
---
<button type="button" class="theme-toggle" aria-label="Toggle dark mode" aria-pressed="false">
  <span class="icon-sun" aria-hidden="true">☀</span>
  <span class="icon-moon" aria-hidden="true">☾</span>
</button>

<script>
  function setup() {
    const button = document.querySelector<HTMLButtonElement>('.theme-toggle');
    if (!button) return;

    const sync = () => {
      const dark = document.documentElement.dataset.theme === 'dark';
      button.setAttribute('aria-pressed', String(dark));
    };
    sync();

    button.addEventListener('click', () => {
      const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
      document.documentElement.dataset.theme = next;
      try { localStorage.setItem('theme', next); } catch {}
      sync();
    });
  }

  setup();
  document.addEventListener('astro:after-swap', setup);
</script>

<style>
  .theme-toggle { background: none; border: 1px solid var(--border); border-radius: 999px; padding: 0.4rem 0.6rem; color: var(--text); cursor: pointer; }
  :global([data-theme='dark']) .icon-sun,
  :global([data-theme='light']) .icon-moon { display: none; }
</style>

aria-pressed tells screen reader users whether dark mode is on, and the icons are hidden from assistive technology because the label already describes the button. The astro:after-swap listener matters only if you use View Transitions, which the next section covers. Without them, setup() runs once per page load, which is all you need.

Step 4: keep the theme across View Transitions

With <ClientRouter /> in your layout, Astro replaces the page without a full reload. During the swap it copies the attributes of the new page’s <html> element onto the current one. The new HTML came from the server with no data-theme, so the theme is wiped and the page flashes light on every navigation.

The fix is to set the theme on the incoming document before the swap happens. Add this to the same inline head script:

---
// src/layouts/BaseLayout.astro (head)
import { ClientRouter } from 'astro:transitions';
---
<ClientRouter />
<script is:inline>
  (() => {
    const getTheme = () => {
      let stored = null;
      try { stored = localStorage.getItem('theme'); } catch {}
      if (stored === 'light' || stored === 'dark') return stored;
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    document.documentElement.dataset.theme = getTheme();
    document.addEventListener('astro:before-swap', (event) => {
      event.newDocument.documentElement.dataset.theme = getTheme();
    });
  })();
</script>

astro:before-swap fires after the new page is fetched and parsed but before it replaces the current one, and event.newDocument is that parsed page. Setting the attribute there means the swap copies the correct theme. Because the inline script lives in the <head> and is identical on every page, the router keeps it rather than re-running it, so the listener is registered once. The View Transitions guide covers the rest of the lifecycle events.

Using Tailwind CSS dark mode

If you style with Tailwind CSS 4, point its dark: variant at the same attribute so the inline script controls both your variables and Tailwind utilities:

/* src/styles/global.css */
@import "tailwindcss";

@custom-variant dark (&:where([data-theme='dark'], [data-theme='dark'] *));

Now class="bg-white dark:bg-slate-950" follows the toggle. On Tailwind CSS 3, set darkMode: ['selector', '[data-theme="dark"]'] in tailwind.config.mjs instead. The full setup is in Tailwind CSS in Astro.

Following the system setting live

The script above reads the system setting once. If you want the site to switch when the operating system switches (for example at sunset), listen for changes, but only when the visitor has not chosen a theme themselves:

// inside the ThemeToggle <script>
const media = window.matchMedia('(prefers-color-scheme: dark)');
media.addEventListener('change', (event) => {
  let stored = null;
  try { stored = localStorage.getItem('theme'); } catch {}
  if (stored) return; // respect an explicit choice
  document.documentElement.dataset.theme = event.matches ? 'dark' : 'light';
});

Some sites offer three options: light, dark and system. That is the same code with a third stored value, 'system', which you treat like no stored value. A three-way switch is friendlier for visitors who want the site to follow their device but occasionally override it.

Images, code blocks and other details

Colors are the easy part. A few other elements need attention in dark mode:

  • Images and logos. Use a <picture> with <source media="(prefers-color-scheme: dark)"> for system-based switching, or render two images and hide one with a [data-theme='dark'] selector when you use a manual toggle.
  • Syntax highlighting. Astro’s built-in Shiki highlighter supports dual themes through markdown.shikiConfig.themes with light and dark keys. It writes both colors as CSS variables, and you switch between them with a few lines of CSS keyed off data-theme.
  • Embedded content. Iframes such as maps or videos cannot inherit your theme. Give them a border so they do not float on a dark background.
  • Contrast. Check muted text and borders in both themes against WCAG AA. Dark themes often fail on gray-on-gray secondary text.

The scoped vs global styles guide explains why the toggle component above uses :global() to read the root attribute, and the styling docs show where theme tokens live in a project.

Many Astro themes ship a light and a dark design; if you start from one, check whether it already has a toggle before adding your own. The MDN references for prefers-color-scheme and color-scheme are worth bookmarking.

FAQ

How do I stop the dark mode flash in Astro?

Set the theme with a <script is:inline> placed in the <head>, before your stylesheets. Inline scripts run while the page is parsed, so the theme attribute is on <html> before the first paint. Bundled scripts run later and cause the flash.

Why does dark mode reset when I navigate with View Transitions?

The router copies the <html> attributes from the new page, which has no theme set. Listen for astro:before-swap and set the theme on event.newDocument.documentElement so the swap carries it over.

Should I use a class or a data attribute for dark mode?

Either works. A data-theme attribute reads clearly and supports more than two themes; a dark class matches Tailwind’s convention. Pick one and use it in both the inline script and your CSS.

Can Astro dark mode work without JavaScript?

Yes, if you only follow the system setting. Use @media (prefers-color-scheme: dark) to override your CSS variables and no script is needed. A manual toggle that remembers the choice needs a small script.

Where should I store the visitor’s theme choice?

localStorage is the usual choice for static sites, because the inline script can read it synchronously. A cookie works too and lets server-rendered pages output the right theme in the HTML, but it requires on-demand rendering.