<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ dark mode - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ dark mode - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:35:18 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/dark-mode/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Set Up and Customize Light and Dark Mode in shadcn with Next.js ]]>
                </title>
                <description>
                    <![CDATA[ If you've created a Next.js project with shadcn/ui recently, there's a good chance dark mode is already set up. I noticed this while looking through a fresh project. I opened app/globals.css expecting ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-and-customize-light-and-dark-mode-in-shadcn-with-next-js/</link>
                <guid isPermaLink="false">6b06284b7f6906157677974a</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ shadcn ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ajay Patel ]]>
                </dc:creator>
                <pubDate>Wed, 25 Nov 2026 00:14:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/cec83f18-c647-46a4-a7ca-125aea525bed.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've created a Next.js project with shadcn/ui recently, there's a good chance dark mode is already set up.</p>
<p>I noticed this while looking through a fresh project. I opened <code>app/globals.css</code> expecting to add the theme colors, but the light and dark values were already there. Then I checked the <code>components</code> folder and found a <code>theme-provider.tsx</code> file that had already been created for me.</p>
<p>That raised a more useful question: if shadcn has already done most of the setup, what do you actually need to build?</p>
<p>In this guide, we'll look at the dark-mode setup that comes with a generated shadcn project, understand how the pieces work together, and build a theme switcher that users can control. We'll also look at how to customize the colors without adding light and dark classes to every component.</p>
<p>By the end, you'll know:</p>
<ul>
<li>Where shadcn stores its light and dark theme values</li>
<li>How CSS variables and Tailwind theme variables work together</li>
<li>What <code>next-themes</code> does in a Next.js project</li>
<li>How to add a two-state or three-option theme switcher</li>
<li>How to add your own theme tokens</li>
</ul>
<p>We'll start with the generated project and work through the theme setup before building the switcher.</p>
<p><strong>Before you start:</strong> This guide follows the Next.js project generated by <a href="https://ui.shadcn.com/create">shadcn/create</a>. Your project may look a little different if you use another framework, an older shadcn setup, or a different component style. I'll point out the parts you should check in your own project.</p>
<p>The examples and screenshots in this article are based on the companion project. Once you have the project locally, you can run <code>pnpm install</code> and <code>pnpm dev</code> to try it yourself.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/b000ee75-6dbb-480e-81cd-d7f39a07533c.png" alt="The companion demo app in light mode." style="display: block;" width="1440" height="900" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/c99c2fb2-3a3b-48db-9846-59bf4be10834.png" alt="The companion demo app in dark mode." style="display: block;" width="1440" height="900" loading="lazy">

<p><em>The same page is shown in both themes. Only the active theme values change.</em></p>
<p>The page uses the same JSX in both screenshots. The theme changes the values behind the CSS variables, and the browser updates the styles.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-project-setup-and-versions">Project Setup and Versions</a></li>
<li><a href="#heading-1-create-a-shadcn-project">1. Create a shadcn Project</a></li>
<li><a href="#heading-2-what-shadcn-has-already-configured">2. What shadcn Has Already Configured</a></li>
<li><a href="#heading-3-where-the-theme-colors-live">3. Where the Theme Colors Live</a><ul>
<li><a href="#heading-why-semantic-tokens-are-useful">Why Semantic Tokens Are Useful</a></li>
<li><a href="#heading-understanding-the-foreground-pairs">Understanding the Foreground Pairs</a></li>
</ul>
</li>
<li><a href="#heading-4-how-tailwind-gets-its-theme-classes">4. How Tailwind Gets its Theme Classes</a><ul>
<li><a href="#heading-what-the-dark-variant-does">What the dark: Variant Does</a></li>
</ul>
</li>
<li><a href="#heading-5-what-next-themes-does">5. What next-themes Does</a></li>
<li><a href="#heading-6-the-theme-provider-thats-already-in-your-project">6. The Theme Provider That's Already in Your Project</a><ul>
<li><a href="#heading-theres-a-keyboard-shortcut-too">There's a Keyboard Shortcut Too</a></li>
<li><a href="#heading-what-the-provider-options-mean">What the Provider Options Mean</a></li>
<li><a href="#heading-why-layouttsx-uses-suppresshydrationwarning">Why layout.tsx Uses suppressHydrationWarning</a></li>
</ul>
</li>
<li><a href="#heading-7-build-a-theme-switcher">7. Build a Theme Switcher</a><ul>
<li><a href="#heading-option-1-a-light-and-dark-toggle">Option 1: A light and Dark Toggle</a></li>
<li><a href="#heading-option-2-a-light-dark-and-system-menu">Option 2: A Light, Dark, and System Menu</a></li>
</ul>
</li>
<li><a href="#heading-8-why-the-icon-animation-may-not-work">8. Why the Icon Animation May Not Work</a></li>
<li><a href="#heading-9-customize-your-theme">9. Customize Your Theme</a><ul>
<li><a href="#heading-change-an-existing-token">Change an Existing Token</a></li>
<li><a href="#heading-add-a-custom-token">Add a Custom Token</a></li>
<li><a href="#heading-when-should-you-use-dark">When Should You Usedark:</a></li>
</ul>
</li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-references">References</a></li>
</ul>
<h2 id="heading-project-setup-and-versions">Project Setup and Versions</h2>
<p>The versions below are the versions used in the companion project, which was generated in August 2026. Shadcn's generated output changes over time, so check your own <code>package.json</code> if you're following along with a newer project.</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Version</th>
</tr>
</thead>
<tbody><tr>
<td><code>next</code></td>
<td><code>16.2.6</code></td>
</tr>
<tr>
<td><code>react</code></td>
<td><code>19.2.4</code></td>
</tr>
<tr>
<td><code>next-themes</code></td>
<td><code>0.4.6</code></td>
</tr>
<tr>
<td><code>@base-ui/react</code></td>
<td><code>1.7.0</code></td>
</tr>
<tr>
<td><code>tailwindcss</code></td>
<td><code>4</code></td>
</tr>
</tbody></table>
<p>The project's <code>components.json</code> includes <code>"style": "base-nova"</code> and <code>"baseColor": "stone"</code>. The <code>base-nova</code> style uses Base UI primitives. This matters when we build the dropdown switcher later, because the Base UI version uses the <code>render</code> prop where many older Radix-based examples use <code>asChild</code>.</p>
<h2 id="heading-1-create-a-shadcn-project">1. Create a shadcn Project</h2>
<p>You don't need to configure Next.js and Tailwind from scratch for this guide. Shadcn's project builder can generate a starter project with the theme setup included.</p>
<p>Open <a href="https://ui.shadcn.com/create">shadcn/create</a> and select <strong>Get Started</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/c16207c2-7609-40bc-8f4d-fbfc8c15685d.png" alt="The shadcn/create page with the Get Started dialog open." style="display: block;" width="1440" height="900" loading="lazy">

<p>Choose the style, base color, chart color, fonts, icon library, and radius from the controls. These choices affect the theme values that will be added to your project. We'll look at those values in the next section.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/9f78e27d-41a8-4885-9cea-8f272f178229.png" alt="The shadcn theme builder with controls for style, colors, fonts, icons, and radius." style="display: block;" width="1440" height="900" loading="lazy">

<p>When you're happy with the setup, select <strong>Get Code</strong>, choose <strong>Next.js</strong>, and copy the command.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/46c4b750-21f1-4da9-9416-dc0b3ba7707a.png" alt="The Get Code dialog with Next.js selected and the generated setup command visible." style="display: block;" width="1440" height="900" loading="lazy">

<p>Run the command in your terminal. The preset ID in your command may be different from the example below:</p>
<pre><code class="language-bash">pnpm dlx shadcn@latest init --preset b0 --template next
</code></pre>
<p>If you're building a complete product, you may prefer to start with a ready-made <a href="https://shadcnstudio.com/templates">shadcn template</a> and adapt it to your app. The same theme setup covered in this guide can be used in a template-based project.</p>
<p>The generated project has a structure similar to this:</p>
<pre><code class="language-plaintext">shadcn-light-dark-theme/
├── app/
│   ├── globals.css          # every theme token, light and dark
│   ├── layout.tsx           # fonts and ThemeProvider already wired
│   └── page.tsx
├── components/
│   ├── theme-provider.tsx   # next-themes, already configured
│   └── ui/button.tsx
├── lib/utils.ts
└── components.json
</code></pre>
<p>Start the development server:</p>
<pre><code class="language-bash">pnpm dev
</code></pre>
<p>Open <code>http://localhost:3000</code>. The companion project also includes a keyboard shortcut: pressing <code>d</code> switches between light and dark mode.</p>
<p>The important point is that the theme setup is already present. Before adding anything, let's see what the generator has configured.</p>
<h2 id="heading-2-what-shadcn-has-already-configured">2. What shadcn Has Already Configured</h2>
<p>A generated project includes most of the pieces you need for light and dark themes. Here's where to find them:</p>
<table>
<thead>
<tr>
<th>Part</th>
<th>Where to find it</th>
<th>Included</th>
</tr>
</thead>
<tbody><tr>
<td>Light theme values</td>
<td><code>app/globals.css</code> then <code>:root</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Dark theme values</td>
<td><code>app/globals.css</code> then <code>.dark</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Tailwind's <code>dark:</code> variant</td>
<td><code>app/globals.css</code> then <code>@custom-variant</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Tailwind utilities for theme tokens</td>
<td><code>app/globals.css</code> then <code>@theme inline</code></td>
<td>Yes</td>
</tr>
<tr>
<td><code>next-themes</code> package</td>
<td><code>package.json</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Theme provider</td>
<td><code>components/theme-provider.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Provider added to the app</td>
<td><code>app/layout.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Hydration warning handling</td>
<td><code>app/layout.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>A visible theme switcher</td>
<td>Your UI</td>
<td><strong>You add this</strong></td>
</tr>
</tbody></table>
<p>So the main piece you'll usually need to add is the control that lets someone choose a theme. The rest is already configured, although it's worth understanding before you start customizing it.</p>
<h2 id="heading-3-where-the-theme-colors-live">3. Where the Theme Colors Live</h2>
<p>Open <code>app/globals.css</code>. You'll find two groups of CSS variables: one inside <code>:root</code> and another inside <code>.dark</code>.</p>
<p>Here's a shortened example based on the generated project:</p>
<pre><code class="language-css">:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.147 0.004 49.25);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.147 0.004 49.25);
  --primary: oklch(0.555 0.163 48.998);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --muted: oklch(0.97 0.001 106.424);
  --muted-foreground: oklch(0.553 0.013 58.071);
  --border: oklch(0.923 0.003 48.717);
  --radius: 0.625rem;
  /* …about thirty in total */
}

.dark {
  --background: oklch(0.147 0.004 49.25);
  --foreground: oklch(0.985 0.001 106.423);
  --card: oklch(0.216 0.006 56.043);
  --card-foreground: oklch(0.985 0.001 106.423);
  --primary: oklch(0.473 0.137 46.201);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --muted: oklch(0.268 0.007 34.298);
  --muted-foreground: oklch(0.709 0.01 56.259);
  --border: oklch(1 0 0 / 10%);
}
</code></pre>
<p>The idea is straightforward:</p>
<pre><code class="language-plaintext">:root   →  light theme values
.dark   →  dark theme values
</code></pre>
<p>Both blocks use the same variable names. The values change depending on whether the <code>dark</code> class is present on the page.</p>
<p>For example, <code>--background</code> is white in the light theme and near-black in the dark theme. <code>--foreground</code> changes in the opposite direction so the text remains visible against the background.</p>
<p>You'll also see variables such as <code>--radius</code>. It isn't a color, but it's part of the theme configuration. In this setup, the radius is defined once because the corner shape doesn't need a separate value for dark mode.</p>
<h3 id="heading-why-semantic-tokens-are-useful">Why Semantic Tokens Are Useful</h3>
<p>Theme variables are especially useful when you're building components. Compare these two examples.</p>
<p>Without semantic tokens, you might add separate light and dark colors directly to the component:</p>
<pre><code class="language-tsx">&lt;div className="bg-white text-black dark:bg-black dark:text-white"&gt;
  Hello
&lt;/div&gt;
</code></pre>
<p>That works, but you have to repeat the same decisions throughout your app. If your color palette changes, you'll need to find and update all those classes.</p>
<p>With semantic tokens, the component can use the theme variable instead:</p>
<pre><code class="language-tsx">&lt;div className="bg-background text-foreground"&gt;
  Hello
&lt;/div&gt;
</code></pre>
<p>The component doesn't need to know whether the page is in light or dark mode. It uses <code>background</code> and <code>foreground</code>, and the active theme supplies the right values.</p>
<p>This is also why shadcn components such as <code>Card</code> can adapt without needing dark-mode classes of their own:</p>
<pre><code class="language-tsx">&lt;Card&gt;
  &lt;CardHeader&gt;
    &lt;CardTitle&gt;Hello&lt;/CardTitle&gt;
  &lt;/CardHeader&gt;
&lt;/Card&gt;
</code></pre>
<p>If you open <code>components/ui/card.tsx</code>, you'll see classes such as <code>bg-card</code> and <code>text-card-foreground</code>. The component uses the semantic tokens, while the theme defines what those tokens look like.</p>
<p>The same idea applies when you add more UI to the project. If you need examples of individual elements built for the shadcn ecosystem, you can refer to <a href="https://shadcnstudio.com/components">Shadcn Components</a> and adapt the ones that fit your interface. Keep the semantic tokens in place so those components follow your light and dark themes.</p>
<h3 id="heading-understanding-the-foreground-pairs">Understanding the Foreground Pairs</h3>
<p>Many theme tokens come in pairs. The first token describes a surface, and the <code>-foreground</code> token describes the text or content that appears on top of it.</p>
<table>
<thead>
<tr>
<th>Surface token</th>
<th>Foreground token</th>
</tr>
</thead>
<tbody><tr>
<td><code>--background</code></td>
<td><code>--foreground</code></td>
</tr>
<tr>
<td><code>--card</code></td>
<td><code>--card-foreground</code></td>
</tr>
<tr>
<td><code>--primary</code></td>
<td><code>--primary-foreground</code></td>
</tr>
<tr>
<td><code>--muted</code></td>
<td><code>--muted-foreground</code></td>
</tr>
</tbody></table>
<p>For example, <code>bg-primary text-primary-foreground</code> uses a matching background and text color. The theme defines both values together so the combination works across its light and dark palettes.</p>
<p>Some tokens, such as <code>--border</code>, <code>--input</code>, and <code>--ring</code>, don't need a foreground pair because they're used for borders, input outlines, and focus indicators.</p>
<p>The companion project displays the token pairs as simple tiles. Each tile uses the same <code>bg-&lt;name&gt; text-&lt;name&gt;-foreground</code> pattern.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/1797b932-d44d-41b2-832d-7855bdc34295.png" alt="Theme token pairs displayed in light mode." style="display: block;" width="721" height="136" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/53a19e7f-cea3-44e9-ac59-67c801297f63.png" alt="The same theme token pairs displayed in dark mode." style="display: block;" width="721" height="136" loading="lazy">

<p>The markup stays the same in both screenshots. Only the active CSS variable values change. The demo also includes a custom <code>--warning</code> token to show how you can extend the theme.</p>
<h2 id="heading-4-how-tailwind-gets-its-theme-classes">4. How Tailwind Gets its Theme Classes</h2>
<p>There's one more part of <code>globals.css</code> that's easy to overlook: the <code>@theme inline</code> block.</p>
<p>A CSS variable such as <code>--primary</code> is available to CSS, but defining it doesn't automatically create Tailwind classes such as <code>bg-primary</code> or <code>text-primary</code>. Tailwind needs to know which variables should become utility classes.</p>
<p>That's what this block does:</p>
<pre><code class="language-css">@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-primary: var(--primary);
  --color-primary-foreground: var(--primary-foreground);
  --color-muted: var(--muted);
  /* …one line per token */
  --radius-sm: calc(var(--radius) * 0.6);
  --radius-md: calc(var(--radius) * 0.8);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) * 1.4);
}
</code></pre>
<p>For example, this line:</p>
<pre><code class="language-css">--color-primary: var(--primary);
</code></pre>
<p>connects the CSS variable <code>--primary</code> to Tailwind's color utilities. It allows you to use classes such as <code>bg-primary</code>, <code>text-primary</code>, and <code>border-primary</code>.</p>
<p>This is an important step when you add your own tokens. If you define <code>--brand</code> in <code>:root</code> but don't add a matching <code>--color-brand</code> entry in <code>@theme inline</code>, Tailwind won't generate the <code>bg-brand</code> utility for you. The CSS variable can exist and still not be available as a Tailwind utility.</p>
<p>The <code>inline</code> keyword is also important here. It allows the generated utilities to reference the underlying CSS variable, so they use the current value when the theme changes.</p>
<h3 id="heading-what-the-dark-variant-does">What the <code>dark:</code> Variant Does</h3>
<p>You'll also find this line in <code>globals.css</code>:</p>
<pre><code class="language-css">@custom-variant dark (&amp;:is(.dark *));
</code></pre>
<p>This defines how Tailwind's <code>dark:</code> variant works in this setup. A class such as <code>dark:hidden</code> applies when the element is inside an ancestor with the <code>dark</code> class.</p>
<p>There are two details to remember:</p>
<ul>
<li>The theme is represented by a <code>dark</code> class, rather than a <code>data-theme</code> attribute.</li>
<li>The selector targets descendants of the element with the <code>dark</code> class.</li>
</ul>
<p>In this project, <code>next-themes</code> adds the class to the <code>&lt;html&gt;</code> element. That means the elements inside the page can use <code>dark:</code> utilities as expected.</p>
<p>Here's the relationship between the theme class, CSS variables, and Tailwind utilities:</p>
<pre><code class="language-plaintext">.dark on &lt;html&gt;
   ↓
--primary changes value          (globals.css)
   ↓
--color-primary reads it         (@theme inline)
   ↓
bg-primary compiles to var(--primary)
   ↓
every element using bg-primary repaints
</code></pre>
<p>When the theme changes, the browser updates the CSS variables and recalculates the styles that use them. Your components don't need to re-render just because a theme color changed.</p>
<p>So far, we've looked at the CSS side. The next question is what adds or removes the <code>dark</code> class.</p>
<h2 id="heading-5-what-next-themes-does">5. What <code>next-themes</code> Does</h2>
<p>CSS defines what the light and dark themes look like. It doesn't remember a visitor's choice or decide which theme should be active. That's handled by JavaScript.</p>
<p>The generated Next.js project uses <a href="https://github.com/pacocoursey/next-themes"><code>next-themes</code></a> for this.</p>
<p>The library handles a few things for you:</p>
<ul>
<li>Adds or removes the <code>dark</code> class on the <code>&lt;html&gt;</code> element.</li>
<li>Saves the selected theme in <code>localStorage</code>.</li>
<li>Supports a <code>system</code> option that follows the visitor's operating system preference.</li>
<li>Runs a small script before the page is displayed so the saved theme can be applied early.</li>
</ul>
<p>That last point helps prevent a flash of the wrong theme when the page loads. If you wait until a React <code>useEffect</code> runs to apply the theme, the browser may display the page before the effect runs. A visitor who prefers dark mode could briefly see the light version first.</p>
<p>The generated project already includes a theme provider and mounts it in the app layout. Let's take a look at what it does.</p>
<h2 id="heading-6-the-theme-provider-thats-already-in-your-project">6. The Theme Provider That's Already in Your Project</h2>
<p>The generated <code>components/theme-provider.tsx</code> file wraps <code>next-themes</code> and sets a few defaults. Here's the provider from the companion project:</p>
<pre><code class="language-tsx">"use client"

import * as React from "react"
import { ThemeProvider as NextThemesProvider, useTheme } from "next-themes"

function ThemeProvider({
  children,
  ...props
}: React.ComponentProps&lt;typeof NextThemesProvider&gt;) {
  return (
    &lt;NextThemesProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
      disableTransitionOnChange
      {...props}
    &gt;
      &lt;ThemeHotkey /&gt;
      {children}
    &lt;/NextThemesProvider&gt;
  )
}
</code></pre>
<p>The wrapper means you don't need to repeat the same configuration every time you use the provider. In <code>app/layout.tsx</code>, it can be mounted like this:</p>
<pre><code class="language-tsx">&lt;ThemeProvider&gt;{children}&lt;/ThemeProvider&gt;
</code></pre>
<p>The <code>{...props}</code> spread comes after the default props. That means a value passed to <code>ThemeProvider</code> can override the wrapper's defaults.</p>
<h3 id="heading-theres-a-keyboard-shortcut-too">There's a Keyboard Shortcut Too</h3>
<p>The provider file also includes a <code>ThemeHotkey</code> component:</p>
<pre><code class="language-tsx">function isTypingTarget(target: EventTarget | null) {
  if (!(target instanceof HTMLElement)) {
    return false
  }

  return (
    target.isContentEditable ||
    target.tagName === "INPUT" ||
    target.tagName === "TEXTAREA" ||
    target.tagName === "SELECT"
  )
}

function ThemeHotkey() {
  const { resolvedTheme, setTheme } = useTheme()

  React.useEffect(() =&gt; {
    function onKeyDown(event: KeyboardEvent) {
      if (event.defaultPrevented || event.repeat) return
      if (event.metaKey || event.ctrlKey || event.altKey) return
      if (event.key.toLowerCase() !== "d") return
      if (isTypingTarget(event.target)) return

      setTheme(resolvedTheme === "dark" ? "light" : "dark")
    }

    window.addEventListener("keydown", onKeyDown)
    return () =&gt; window.removeEventListener("keydown", onKeyDown)
  }, [resolvedTheme, setTheme])

  return null
}
</code></pre>
<p>This component doesn't render anything on the page. It listens for the <code>d</code> key and switches between light and dark mode.</p>
<p>Notice the checks inside the keyboard handler. They prevent the shortcut from firing when the user is typing in an input, textarea, select, or editable element. The modifier-key check also prevents the shortcut from interfering with combinations such as <code>Cmd+D</code> or <code>Ctrl+D</code>.</p>
<p>If you don't want this shortcut in your project, remove <code>&lt;ThemeHotkey /&gt;</code> from the provider. If you keep it, consider mentioning it somewhere in your app so users know it's available.</p>
<h3 id="heading-what-the-provider-options-mean">What the Provider Options Mean</h3>
<table>
<thead>
<tr>
<th>Option</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>attribute="class"</code></td>
<td>Adds a class to <code>&lt;html&gt;</code> instead of a <code>data-theme</code> attribute.</td>
</tr>
<tr>
<td><code>defaultTheme="system"</code></td>
<td>Uses the operating system preference for a first-time visitor.</td>
</tr>
<tr>
<td><code>enableSystem</code></td>
<td>Enables the <code>system</code> theme option.</td>
</tr>
<tr>
<td><code>disableTransitionOnChange</code></td>
<td>Temporarily disables CSS transitions while the theme changes.</td>
</tr>
</tbody></table>
<p>The <code>attribute="class"</code> setting needs to match the CSS setup from the earlier section. The generated stylesheet looks for <code>.dark</code>, so <code>next-themes</code> needs to add a class. If you change the attribute to <code>data-theme</code>, the <code>.dark</code> selector won't match unless you also update your CSS.</p>
<p>If your switcher uses animated icons, this setting can affect their transitions. The behavior is worth considering when you decide how theme changes should look across the page.</p>
<h3 id="heading-why-layouttsx-uses-suppresshydrationwarning">Why <code>layout.tsx</code> Uses <code>suppressHydrationWarning</code></h3>
<p>You may also notice this on the <code>&lt;html&gt;</code> element in <code>app/layout.tsx</code>:</p>
<pre><code class="language-tsx">&lt;html lang="en" suppressHydrationWarning className={cn("antialiased", …)}&gt;
</code></pre>
<p>The theme script can update the <code>&lt;html&gt;</code> class before React hydrates the page. That means the HTML rendered on the server may have a different class from the HTML React sees in the browser.</p>
<p><code>suppressHydrationWarning</code> tells React to suppress that expected warning on this element. It's included in the generated setup for this reason. It applies to that element, rather than disabling hydration warnings throughout the app.</p>
<h2 id="heading-7-build-a-theme-switcher">7. Build a Theme Switcher</h2>
<p>At this point, the theme colors are configured and <code>next-themes</code> can apply the selected theme. What the project still needs is a visible control that lets users change it.</p>
<p>There are two common approaches. You can give users a button that switches between light and dark, or offer a menu with Light, Dark, and System options.</p>
<h3 id="heading-option-1-a-light-and-dark-toggle">Option 1: A light and Dark Toggle</h3>
<p>If your app only needs two modes, a single button is enough:</p>
<pre><code class="language-tsx">"use client"

import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"

import { Button } from "@/components/ui/button"

function ModeSwitch() {
  const { resolvedTheme, setTheme } = useTheme()

  return (
    &lt;Button
      variant="ghost"
      size="icon"
      aria-label="Toggle theme"
      onClick={() =&gt; setTheme(resolvedTheme === "dark" ? "light" : "dark")}
    &gt;
      &lt;Sun className="dark:hidden" /&gt;
      &lt;Moon className="hidden dark:block" /&gt;
    &lt;/Button&gt;
  )
}

export { ModeSwitch }
</code></pre>
<p>A few details in this component are worth understanding.</p>
<p>First, use <code>resolvedTheme</code> for a two-state toggle. The <code>theme</code> value can be <code>"system"</code>, while <code>resolvedTheme</code> tells you which theme is currently active: <code>"light"</code> or <code>"dark"</code>. Since this button switches between two visible states, <code>resolvedTheme</code> is the value you want to check.</p>
<p>Second, keep both icons in the DOM. The <code>Sun</code> and <code>Moon</code> icons are shown or hidden with CSS classes. This avoids choosing an icon based on a theme value that may not be available during server rendering.</p>
<p>For comparison, this conditional approach can cause a mismatch between the server-rendered markup and the browser's first render:</p>
<pre><code class="language-tsx">{resolvedTheme === "dark" ? &lt;Moon /&gt; : &lt;Sun /&gt;}
</code></pre>
<p>Finally, add an accessible label. Since the button only contains an icon, <code>aria-label</code> gives screen reader users a useful description of what the button does.</p>
<h3 id="heading-option-2-a-light-dark-and-system-menu">Option 2: A Light, Dark, and System Menu</h3>
<p>If you want users to choose their preferred mode, including the operating system setting, use a dropdown menu.</p>
<p>First, add the dropdown menu component if it's not already in your project:</p>
<pre><code class="language-bash">pnpm dlx shadcn@latest add dropdown-menu
</code></pre>
<p>Then create the switcher:</p>
<pre><code class="language-tsx">"use client"

import { ChevronDown, Monitor, Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

const MODES = [
  { value: "light", label: "Light", icon: Sun },
  { value: "dark", label: "Dark", icon: Moon },
  { value: "system", label: "System", icon: Monitor },
]

function ModeToggle() {
  const { theme, setTheme } = useTheme()

  return (
    &lt;DropdownMenu&gt;
      &lt;DropdownMenuTrigger
        render={&lt;Button variant="ghost" aria-label="Change theme" /&gt;}
      &gt;
        &lt;Sun className="dark:hidden" /&gt;
        &lt;Moon className="hidden dark:block" /&gt;
        &lt;ChevronDown className="size-3 text-muted-foreground" /&gt;
      &lt;/DropdownMenuTrigger&gt;
      &lt;DropdownMenuContent align="end" className="min-w-36"&gt;
        &lt;DropdownMenuRadioGroup
          value={theme ?? "system"}
          onValueChange={(value) =&gt; setTheme(value as string)}
        &gt;
          {MODES.map(({ value, label, icon: Icon }) =&gt; (
            &lt;DropdownMenuRadioItem key={value} value={value}&gt;
              &lt;Icon className="text-muted-foreground" /&gt;
              {label}
            &lt;/DropdownMenuRadioItem&gt;
          ))}
        &lt;/DropdownMenuRadioGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  )
}

export { ModeToggle }
</code></pre>
<p>The menu uses a radio group so the current option is shown as selected. This makes it easier for users to see whether Light, Dark, or System is active.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/537f5bff-efb1-4a39-8eb2-5c8cd2b21cc4.png" alt="The demo header showing the theme switchers, with the custom warning-token example below." style="display: block;" width="1440" height="900" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/5e0e37c4-76ab-4138-8574-c5e632d44f5f.png" alt="5e0e37c4-76ab-4138-8574-c5e632d44f5f" style="display: block;" width="1440" height="900" loading="lazy">

<p>There are two implementation details to pay attention to here.</p>
<p>First, base UI uses <code>render</code> instead of <code>asChild</code>. The companion project uses the <code>base-nova</code> style, which is built on Base UI. In this setup, the dropdown trigger uses the <code>render</code> prop to render the shadcn button. Many older examples use <code>asChild</code>, which is common in Radix-based projects. Check your own <code>components.json</code> and component imports before copying an example.</p>
<p>Use a radio group for mutually exclusive options. Light, Dark, and System are three choices where only one can be active at a time. <code>DropdownMenuRadioGroup</code> communicates that relationship and displays the selected option.</p>
<p>The expression <code>theme ?? "system"</code> uses <code>"system"</code> as a fallback if the theme value is still undefined. This keeps the radio group controlled while <code>next-themes</code> initializes.</p>
<p>You may have seen the <code>next-themes</code> advice to wait until a component has mounted before rendering anything based on <code>theme</code>. That advice is for UI the server renders. Here, the radio items only appear when someone opens the menu, which always happens after the page has hydrated, so the server never renders a theme value and there's nothing to mismatch.</p>
<p>You can now place the switcher in your header or another part of your layout. For example:</p>
<pre><code class="language-tsx">import { ModeToggle } from "@/components/mode-toggle"

&lt;header className="flex h-14 items-center justify-between border-b px-6"&gt;
  &lt;h1 className="text-sm font-medium"&gt;My app&lt;/h1&gt;
  &lt;ModeToggle /&gt;
&lt;/header&gt;
</code></pre>
<p>Choose one switcher for your app, based on how much control you want to give users. You don't need to display both versions at once.</p>
<p>The switcher will usually sit inside a larger page, such as an account settings screen or dashboard. If you're building that kind of page, <a href="https://shadcnstudio.com/blocks">shadcn blocks</a> can give you useful layout examples. You can adapt a block to your needs and keep using the same theme tokens for its backgrounds, borders, and text.</p>
<h2 id="heading-8-why-the-icon-animation-may-not-work">8. Why the Icon Animation May Not Work</h2>
<p>You might want the sun and moon icons to rotate or scale when someone changes the theme. The shadcn examples include transition classes like these:</p>
<pre><code class="language-tsx">&lt;Sun className="scale-100 rotate-0 transition-transform dark:scale-0 dark:-rotate-90" /&gt;
&lt;Moon className="absolute scale-0 rotate-90 transition-transform dark:scale-100 dark:rotate-0" /&gt;
</code></pre>
<p>But the generated provider also uses <code>disableTransitionOnChange</code>. This option temporarily injects a stylesheet that disables transitions while the theme is changing. The rule used by the installed <code>next-themes</code> version is:</p>
<pre><code class="language-css">*,*::before,*::after{transition:none!important}
</code></pre>
<p>Because the rule uses <code>!important</code>, it can override the <code>transition-transform</code> classes on the icons during the theme change. The icons may switch immediately instead of animating.</p>
<p>There's a reason this option exists. Without it, every element with a CSS transition may animate its colors when the theme changes. Depending on your design, that can make the entire page feel slow or distracting.</p>
<p>You have a few options:</p>
<ul>
<li>Keep <code>disableTransitionOnChange</code> and use icons without transition effects.</li>
<li>Remove the option if you want the page and icons to transition together.</li>
<li>Keep the option and use a CSS animation or a motion library for the icon effect. Test this with your actual setup to make sure the animation behaves as expected.</li>
</ul>
<p>The important thing is to understand that the provider setting affects more than the theme colors. It can also affect transitions elsewhere in your interface.</p>
<h2 id="heading-9-customize-your-theme">9. Customize Your Theme</h2>
<p>Once you understand where the theme values live, changing your app's colors becomes much easier. You can update a token once and have every component that uses it pick up the new value.</p>
<h3 id="heading-change-an-existing-token">Change an Existing Token</h3>
<p>Imagine your brand uses blue as its primary color. You could set a blue background directly on one button:</p>
<pre><code class="language-tsx">&lt;Button className="bg-blue-500 dark:bg-blue-700"&gt;Save&lt;/Button&gt;
</code></pre>
<p>But this only changes that button. If you want the primary color to be consistent across your app, update the <code>--primary</code> token in <code>app/globals.css</code> instead:</p>
<pre><code class="language-css">:root {
  --primary: oklch(0.55 0.18 265);
  --primary-foreground: oklch(0.99 0 0);
}

.dark {
  --primary: oklch(0.62 0.16 265);
  --primary-foreground: oklch(0.17 0.02 265);
}
</code></pre>
<p>The same token is used by components and utilities throughout the project. Update both the <code>:root</code> and <code>.dark</code> values so the color works in both themes.</p>
<p>The two values don't have to be identical. A color that looks good on a light background may need a different lightness or saturation on a dark background. The generated theme uses different values for some tokens for exactly this reason.</p>
<p>The project also uses <code>oklch()</code> color values. In this color format, the first value represents lightness, which can make it easier to adjust how bright or dark a color appears while keeping its hue consistent.</p>
<p>You can customize the border radius in the same way. The generated <code>@theme inline</code> block derives several radius utilities from the <code>--radius</code> value, so changing it updates the overall corner scale:</p>
<pre><code class="language-css">--radius: 0.625rem;
</code></pre>
<h3 id="heading-add-a-custom-token">Add a Custom Token</h3>
<p>You can also add tokens that aren't included in the default theme. For example, let's add a <code>warning</code> color that can be used for a notice or alert.</p>
<p>First, define the token and its foreground color in both theme blocks. Then connect those variables to Tailwind in <code>@theme inline</code>:</p>
<pre><code class="language-css">:root {
  --warning: oklch(0.84 0.16 84);
  --warning-foreground: oklch(0.28 0.07 46);
}

.dark {
  --warning: oklch(0.41 0.11 46);
  --warning-foreground: oklch(0.99 0.02 95);
}

@theme inline {
  --color-warning: var(--warning);
  --color-warning-foreground: var(--warning-foreground);
}
</code></pre>
<p>You can now use the new classes in a component:</p>
<pre><code class="language-tsx">&lt;div className="bg-warning text-warning-foreground rounded-lg p-3"&gt;
  Your trial ends in 3 days.
&lt;/div&gt;
</code></pre>
<p>The component uses the same classes in both screenshots. The theme supplies the appropriate background and text colors.</p>
<p>Remember to add the <code>--color-warning</code> and <code>--color-warning-foreground</code> entries to <code>@theme inline</code>. Without those entries, the CSS variables will exist, but Tailwind won't generate the corresponding utility classes.</p>
<p>It's also a good idea to define a foreground token whenever you add a new surface color. That way, the background and text colors are designed to work together.</p>
<h3 id="heading-when-should-you-use-dark">When Should You Use <code>dark:</code></h3>
<p>Once your theme uses semantic tokens, you won't need <code>dark:</code> classes for most background and text colors.</p>
<p>For example, instead of maintaining separate light and dark background classes:</p>
<pre><code class="language-tsx">// You're now maintaining this color in two places
&lt;div className="bg-slate-100 dark:bg-slate-800"&gt;

// The token already knows
&lt;div className="bg-muted"&gt;
</code></pre>
<p>Use a semantic token such as <code>bg-muted</code> when it represents the color you want. The token already has values for both themes.</p>
<p>There are still cases where <code>dark:</code> is useful. You might need to swap an image, adjust a shadow, or change a decorative element that doesn't fit into your semantic color tokens. Use it when the appearance genuinely needs a theme-specific rule.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A generated shadcn project already includes most of the setup needed for light and dark mode. The part you usually need to build is the switcher that gives users control over the theme.</p>
<p>Here's a quick recap:</p>
<ol>
<li><code>:root</code> and <code>.dark</code> define the theme values. They use the same variable names with different values.</li>
<li><code>@theme inline</code> connects CSS variables to Tailwind utilities**.** Add a matching entry when you create a custom token.</li>
<li><code>next-themes</code> applies the active theme. In this setup, it adds or removes the <code>dark</code> class on <code>&lt;html&gt;</code>.</li>
<li>The generated project already includes the provider. Check <code>components/theme-provider.tsx</code> and <code>app/layout.tsx</code> before creating another one.</li>
<li>The visible switcher is the part you add. Use a simple toggle or a menu with Light, Dark, and System options.</li>
<li>Customize tokens instead of styling every component separately. This keeps your colors consistent across the app.</li>
</ol>
<p>Once you know how these pieces fit together, dark mode becomes easier to maintain. You can update the theme in one place, add new tokens when you need them, and let your components use those values without having to check which theme is active.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a href="https://ui.shadcn.com/create">shadcn/create</a>: Generate a shadcn project.</li>
<li><a href="https://ui.shadcn.com/docs/dark-mode/next">shadcn dark mode for Next.js</a>: Official Next.js dark-mode setup.</li>
<li><a href="https://ui.shadcn.com/docs/theming">shadcn theming</a>: Theme tokens and CSS variables.</li>
<li><a href="https://github.com/pacocoursey/next-themes">next-themes</a>: Theme provider documentation and source.</li>
<li><a href="https://tailwindcss.com/docs/theme">Tailwind CSS theme variables</a>: How theme variables create utility classes.</li>
<li><a href="https://base-ui.com/">Base UI</a>: Documentation for the primitives used by the <code>base-nova</code> style.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch">MDN: <code>oklch()</code></a>: Reference for the OKLCH color format.</li>
</ul>
<h4 id="heading-thanks-for-reading">Thanks for Reading</h4>
<p>The companion project includes both switcher examples, the custom <code>warning</code> token, and the page used for the screenshots. To try the examples locally, clone the repository, then run <code>pnpm install</code> followed by <code>pnpm dev</code> from the project directory.</p>
<p>Companion GitHub repository:- <a href="https://github.com/shadcnstudio/shadcn-dark-mode-guide">https://github.com/shadcnstudio/shadcn-dark-mode-guide</a></p>
<p>If you try the examples and run into something that behaves differently in your setup, leave a comment with your shadcn style and package versions. That context makes it much easier to work out what's happening.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Dark Mode Toggle Without JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Over the years, I've worked on many Static Site Generated (SSG) websites that work without JavaScript. And during that time, I've created a few solutions. One of them is a dark mode toggle that doesn' ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-dark-mode-toggle-without-javascript/</link>
                <guid isPermaLink="false">6a4bb3bf6aa89de94c683aa8</guid>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jakub T. Jankiewicz ]]>
                </dc:creator>
                <pubDate>Mon, 06 Jul 2026 13:55:11 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/166e89af-ab96-48c8-bf0b-cbc5972aad2c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Over the years, I've worked on many Static Site Generated (SSG) websites that work without JavaScript. And during that time, I've created a few solutions. One of them is a dark mode toggle that doesn't require JavaScript.</p>
<p>I created this solution for my <a href="https://jakub.jankiewicz.org/blog/">own blog</a>, and then I enhanced it for the <a href="https://wikizeit.edu.pl/">WikiZEIT project</a>. I also included the improved version in my <a href="https://complite.jcubic.pl/">Eleventy starter "Complite"</a>.</p>
<p>In this article, I'll explain how to create a dark mode toggle with just HTML and CSS with help from the new <code>:has()</code> selector. I will also use CSS variables.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ul>
<li><p><a href="#heading-why-should-websites-work-without-javascript">Why Should Websites Work Without JavaScript?</a></p>
</li>
<li><p><a href="#heading-html-structure">HTML Structure</a></p>
</li>
<li><p><a href="#heading-css-code">CSS Code</a></p>
<ul>
<li><p><a href="#heading-styling-the-toggle">Styling the Toggle</a></p>
</li>
<li><p><a href="#heading-css-variables-and-the-website-style">CSS Variables and the Website Style</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-why-should-websites-work-without-javascript">Why Should Websites Work Without JavaScript?</h2>
<p>If you're wondering why a website may benefit from using no JavaScript, there are several reasons, like accessibility (a11y), SEO, and AI visibility.</p>
<p>Modern screen readers can handle JavaScript websites, but this isn't the only thing you should care about. People might be using old computers or phones. Others might have poor internet connections and may disable JavaScript to use less bandwidth.</p>
<p>As for SEO, Google is one of the few major crawlers that can reliably render JavaScript-heavy pages, but rendering can still take extra time compared with indexing server-rendered HTML. Many AI crawlers and answer engines don't appear to execute JavaScript the way a browser does. They often work from the raw HTML response.</p>
<p>So if, for example, you have a React app that's purely client-side rendered, a bot that only reads the initial HTML may see little more than <code>&lt;div id="root"&gt;&lt;/div&gt;</code> until JavaScript runs.</p>
<p>To be clear, the issue isn't React itself, but client-side rendering. Server-side rendering, static generation, or prerendering can make your content available in the initial HTML so search engines and AI crawlers can read it more reliably.</p>
<p>But the point remains: if you want your website to be reliably more accessible to all people and machines, you should make it work even without JavaScript.</p>
<p>Note that your website doesn't need to be written in pure/only HTML and CSS. As mentioned above, if you use solutions like React, consider also using a framework like <a href="https://nextjs.org/">Next.js</a> with Static Site Rendering (SSR) or a Static Site Generator (SSG) like <a href="https://gohugo.io/">Hugo</a>. You can also consider modern SSG solutions like <a href="https://www.11ty.dev/">Eleventy</a> that I'm using.</p>
<p>To learn more about Elventy and Hugo, you can read those two articles:</p>
<ul>
<li><p><a href="https://www.freecodecamp.org/news/your-first-hugo-blog-a-practical-guide/">How to Create Your First Hugo Blog: a Practical Guide</a></p>
</li>
<li><p><a href="https://www.freecodecamp.org/news/learn-eleventy/">Learn the Eleventy Static Site Generator by Building and Deploying a Portfolio Website</a></p>
</li>
</ul>
<p>To learn more about Next.js, you can <a href="https://www.youtube.com/results?search_query=Next.js+tutorial">search videos on YouTube</a> (but remember to check if they explain the modern App Router, not the old Page Router).</p>
<h2 id="heading-html-structure">HTML Structure</h2>
<p>Alright, now that you understand why this approach can be useful, let's dive in and build our dark mode toggle. The HTML of the toggle uses HTML radio buttons:</p>
<pre><code class="language-html">&lt;div class="theme-toggle"&gt;
    &lt;input type="radio" id="mode_dark"
           name="mode" value="dark"&gt;
    &lt;label for="mode_dark"
           aria-label="Switch to dark mode"&gt;
      🌙
    &lt;/label&gt;
    &lt;input type="radio" id="mode_light"
            name="mode" value="light"&gt;
    &lt;label for="mode_light"
           aria-label="Switch to light mode"&gt;
      ☀️
     &lt;/label&gt;
&lt;/div&gt;
</code></pre>
<p>The above code uses moon and sun emojis.</p>
<h2 id="heading-css-code">CSS Code</h2>
<p>Now let's see the CSS part of the solution. The trick to making this work without JavaScript involves using this CSS <code>:has</code> pseudo-class:</p>
<pre><code class="language-css">:has(#mode_dark:checked)
</code></pre>
<p>The way this works is a bit like a parent selector that was always missing in CSS. If you have some code like this <code>p:has(img)</code>, it will match all <code>&lt;p&gt;</code> tags that have images inside.</p>
<p>In our case, <code>:has</code> will match when there's a radio button or checkbox selected anywhere on the page. This is the <code>:checked</code> part and and <code>#mode_dark</code> is the <code>id</code> of the input for the dark mode that we have in the <a href="#heading-html-structure">HTML Structure</a> section.</p>
<p>So to summarize, you can add <code>:has</code> to any element that can be styled when dark mode is selected. Here's an example:</p>
<pre><code class="language-css">html:has(#mode_dark:checked) p {
  color: white;
  background: black;
}
</code></pre>
<p>This CSS will style all <code>&lt;p&gt;</code> tags when dark mode is enabled.</p>
<p>The above example (plus the HTML) is everything you need to create a CSS-only dark mode switch.</p>
<h3 id="heading-styling-the-toggle">Styling the Toggle</h3>
<p>Here's the CSS that styles the toggle so only one emoji (sun or moon) is displayed at a time. This is only to make the toggle look nice.</p>
<p>The code also makes sure that the initially selected value is always the system-preferred mode.</p>
<pre><code class="language-css">/* style of the toggle */
.theme-toggle {
  display: flex;
  align-items: center;
}

/* hide the input */
.theme-toggle input[type="radio"] {
  appearance: none;
  -webkit-appearance: none;
  margin: 0;
  position: absolute;
  opacity: 0;
  pointer-events: none;
}
.theme-toggle label {
    width: 40px; height: 40px;
    display: grid;
    place-items: center;
    cursor: pointer;
}

/* icon visibility
 *
 * default light with system and radio button overwrite
 */
label[for="mode_light"] { display: none; }
label[for="mode_dark"] { display: grid; }

@media (prefers-color-scheme: dark) {
  label[for="mode_light"] { display: grid; }
  label[for="mode_dark"] { display: none; }
}
:root:has(#mode_dark:checked) label[for="mode_light"] {
   display: grid;
}
:root:has(#mode_dark:checked) label[for="mode_dark"] {
   display: none;
}
:root:has(#mode_light:checked) label[for="mode_light"] {
   display: none;
}
:root:has(#mode_light:checked) label[for="mode_dark"] {
   display: grid;
}
</code></pre>
<p>The <code>:root</code> selector above means the root of the HTML tree. It's often used instead of <code>html</code>.</p>
<p>The CSS code <code>@media (prefers-color-scheme: dark)</code> is a media query, a way to add CSS code when special conditions are met. Here the media query is checking whether the user has system settings set to dark mode.</p>
<p>The code hides the inputs, and the labels control the toggle of the radio button. This is a common way to style radio buttons and checkboxes.</p>
<div>
<div>💡</div>
<div>The toggle always displays the mode that it's switching into. That's why in dark mode the sun is showing, not the moon.</div>
</div>

<h3 id="heading-css-variables-and-the-website-style">CSS Variables and the Website Style</h3>
<p>The last part is to style the website. Here we have CSS variables with only two colors. But in a real website, you might have all colors and settings for the dark/light mode that's applied to the whole page:</p>
<pre><code class="language-css">@media (prefers-color-scheme: dark) {
  :root {
    --bg: #252525; /* dark gray */
    --fg: #fff;    /* white */
  }
}
:root:has(#mode_dark:checked) {
  --bg: #252525; /* dark gray */
  --fg: #fff;    /* white */
}
:root:has(#mode_light:checked) {
  --bg: #fff;    /* white */
  --fg: #252525; /* dark gray */
}
</code></pre>
<p>It's useful to use CSS variables because you can put styles that change between dark and light mode in one place. And then you can use one variable instead of hardcoding each style all over your CSS file.</p>
<p>So instead of using code like this:</p>
<pre><code class="language-css">html:has(#mode_dark:checked) p {
  color: #fff;
  background: #252525;
}
</code></pre>
<p>You can use variables:</p>
<pre><code class="language-css">html:has(#mode_dark:checked) p {
    background: var(--bg);
    color: var(--fg);
}
</code></pre>
<p>In case of background and foreground colors, you only need this code:</p>
<pre><code class="language-css">body {
  background: var(--bg);
  color: var(--fg);
}
</code></pre>
<p>You can read more about CSS variables with the <code>:root</code> selector in this article:</p>
<ul>
<li><a href="https://www.freecodecamp.org/news/what-are-css-variables-and-how-to-use-them/">CSS Variables Definition – What are CSS Vars and How to Use Them?</a></li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>When creating a website, it's always worth making it work without JavaScript. It's good for accessibility and SEO.</p>
<p>Now with modern CSS, most of the things a website needs can be done without JS. You should incorporate <a href="https://en.wikipedia.org/wiki/Progressive_enhancement">progressive enhancement</a> and add JavaScript on top of the existing HTML/CSS foundation.</p>
<p>To read more about progressive enhancement, check this article: <a href="https://www.freecodecamp.org/news/what-is-progressive-enhancement-and-why-it-matters-e80c7aaf834a/">What is Progressive Enhancement, and why it matters</a>.</p>
<p>And here is a <a href="https://codepen.io/jcubic/pen/myRqrmj">CodePen demo of the whole solution</a>.</p>
<p>If you have any questions, you can contact me on <a href="https://x.com/jcubic">Twitter/X</a>. My DMs are open. You can also check out my <a href="https://jakub.jankiewicz.org/blog/">personal blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Code Dark Mode for Google Sheets with Apps Script and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Google Sheets is a great tool for working and collaborating on spreadsheets, but it doesn't have native support for dark mode.  In this article, we'll create our own dark mode. One way to do that would be by selecting all the cells and manually chang... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-code-dark-mode-for-google-sheets/</link>
                <guid isPermaLink="false">66b8de03753e1e313e83948f</guid>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ google apps script ]]>
                    </category>
                
                    <category>
                        <![CDATA[ google sheets ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eamonn Cottrell ]]>
                </dc:creator>
                <pubDate>Wed, 20 Sep 2023 22:23:15 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/code-your-own-dark-mode.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Google Sheets is a great tool for working and collaborating on spreadsheets, but it doesn't have native support for dark mode. </p>
<p>In this article, we'll create our own dark mode. One way to do that would be by selecting all the cells and manually changing their background color and font color. This will get the job done, but we can automate the process and add more style options to choose from.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/automate-2.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of cartoon character grabbing a computer</em></p>
<p>Here’s what we’ll build: a style selector that has four different styles triggered by either a new dropdown menu or by clicking a custom button icon.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/1-12.png" alt="Image" width="600" height="400" loading="lazy">
<em>screenshot of Google Sheets with different background modes</em></p>
<p>And here's the video walkthrough if you'd like to follow along with that instead: </p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/TxSGuXPav70" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-how-to-create-dark-mode-in-apps-script">How to Create Dark Mode in Apps Script</h2>
<p>We’ll create four functions, one for each style mode. Each of our functions will do the following:</p>
<ol>
<li>Set background color</li>
<li>Set font color</li>
<li>Set font family</li>
<li>Set border color and style</li>
</ol>
<p>Let’s walk through how to create a <code>darkMode</code> function in <a target="_blank" href="https://script.google.com/home/start">Apps Script</a>. We'll define each function with the <code>function</code> keyword, followed by whatever we’ll name it.</p>
<p>Because the functions take no arguments (they just run without needing more info from us). That is, we have open and closed parentheses with nothing inside them followed by an open curly brace.</p>
<p>All of our code for the function goes between the <code>darkMode</code> function's curly braces:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">darkMode</span>(<span class="hljs-params"></span>) </span>{
  SpreadsheetApp.getActive().getRange(<span class="hljs-string">'A1:Z'</span>)
    .setBackground(<span class="hljs-string">"#333333"</span>)
    .setFontColor(<span class="hljs-string">"white"</span>)
    .setFontFamily(<span class="hljs-string">"Google Sans"</span>)
    .setBorder(<span class="hljs-literal">false</span>,<span class="hljs-literal">false</span>,<span class="hljs-literal">false</span>,<span class="hljs-literal">false</span>,<span class="hljs-literal">true</span>,
     <span class="hljs-literal">true</span>,<span class="hljs-string">"#444444"</span>,SpreadsheetApp.BorderStyle.SOLID)
}
</code></pre>
<p>To select all the cells, we used the built-in methods from the <code>SpreadsheetApp</code> class: <code>getActive()</code> and <code>getRange()</code>. These select the active sheet as well as a given range.</p>
<p>In our case, we’ll plug in <code>A1:Z</code> as the range, but you can extend this further if you’d like. For instance,  <code>A1:AZ</code>, would add columns <code>AA:AZ</code> and then apply our styling to them.</p>
<p>The four lines that follow are simply dot notation extensions telling what styles to apply. You can write this on one line if you’d like, but it’s good practice to have line breaks to make the code easy to read.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/clever.gif" alt="Image" width="600" height="400" loading="lazy">
<em>gif of man saying, that’s clever</em></p>
<h2 id="heading-how-to-set-colors-and-fonts">How to Set Colors and Fonts</h2>
<p>You'd notice that we used both <code>setBackground(#333333)</code> and <code>setFontColor("white")</code> in the code. This is because we can use CSS notation colors in either hex format or by using the color’s name.</p>
<p>Using <code>setFontFamily("Google Sans")</code>, we gave it the font family name within quotations. Being a Google product, you can use any of the <a target="_blank" href="https://fonts.google.com/">Google Fonts</a> as well as Google’s own Google Sans font as I found out making this project.</p>
<h2 id="heading-how-to-set-the-border">How to set the Border</h2>
<p>The <code>setBorder(false,false,false,false,true, true,"#444444",SpreadsheetApp.BorderStyle.SOLID)</code> function let’s you enter <code>true</code> or <code>false</code> values for the top, left, bottom, right, vertical, or horizontal borders, in that order, followed by the color and style.</p>
<p>To set the style, we had to invoke a built in <a target="_blank" href="https://developers.google.com/apps-script/reference/document/attribute">Enum Attribute</a> — <code>BorderStyle</code> — to change the style of the border.</p>
<h2 id="heading-how-to-create-the-style-menu">How to Create the Style Menu</h2>
<p>To be able to select any of the styles we’re making from the actual spreadsheet, we need a menu.</p>
<p>To add the menu, we'll create a new function called  <code>onOpen()</code> that runs as soon as the spreadsheet opens and then the built-in methods from the <code>getUi()</code> to build our custom menu.</p>
<p>We can create the menu with <code>.createMenu()</code> and then add each of our functions to the menu with the <code>addItem()</code> function.</p>
<p>Here's the code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onOpen</span>(<span class="hljs-params"></span>)</span>{
  SpreadsheetApp.getUi()
    .createMenu(<span class="hljs-string">'Style'</span>)
    .addItem(<span class="hljs-string">"Dark"</span>,<span class="hljs-string">"darkMode"</span>)
    .addItem(<span class="hljs-string">"Papyrus"</span>,<span class="hljs-string">"papyrusMode"</span>)
    .addItem(<span class="hljs-string">"Light"</span>,<span class="hljs-string">"lightMode"</span>)
    .addItem(<span class="hljs-string">"Synth"</span>,<span class="hljs-string">"synthMode"</span>)
    .addToUi();
}
</code></pre>
<p>Google Apps Script automatically integrates with Google Workspace apps (like Google Sheets) so the functions we've added in the code will make the functionalities accessible in your Google Sheets.</p>
<h2 id="heading-how-to-add-icon-buttons">How to Add Icon Buttons</h2>
<p>As a bonus, I added four icon images to the sheet, and by selecting <code>Assign script</code> we can have these icons act as buttons to trigger any of the four styles we’ve built:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/2.png" alt="Image" width="600" height="400" loading="lazy">
<em>screenshot of icons in spreadsheet</em></p>
<p>When you type the function name into the Assign script dialog box, make sure you do not to use parentheses. You should only enter the name of the function itself:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/3.png" alt="Image" width="600" height="400" loading="lazy">
<em>screenshot of assigning script to image</em></p>
<p>And bingo! We’ve got ourselves a style picker. You can add or edit these to create any number of combinations that you can easily toggle on and off in your own Google Sheet!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/4.png" alt="Image" width="600" height="400" loading="lazy">
<em>screenshot of Synth Mode Style</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article shows how you can create can code dark, and other background modes for your Google Sheets using Apps Script and JavaScript.</p>
<p>I hope this has been useful for you!</p>
<h2 id="heading-more-resources">More Resources😄</h2>
<p>▶ Find all my video tutorials and walkthroughs on YouTube: <a target="_blank" href="https://www.youtube.com/@eamonncottrell?sub_confirmation=1">https://www.youtube.com/@eamonncottrell?sub_confirmation=1</a></p>
<p>▶ Connect with me on LinkedIn where I share daily tips: <a target="_blank" href="https://www.linkedin.com/in/eamonncottrell/">https://www.linkedin.com/in/eamonncottrell/</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Turn On Dark Mode on Google – Chrome Black Theme Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ These days, lots of developers like to use dark mode. And it's no surprise, as activating dark mode reduces eye strain and leads to better eye health. It also helps both machines and humans perform better overall. In this article, I will show you how... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-turn-on-dark-mode-on-google-chrome-black-theme-tutorial/</link>
                <guid isPermaLink="false">66adf149febac312b73075b6</guid>
                
                    <category>
                        <![CDATA[ Android ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google Chrome ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Fri, 08 Oct 2021 19:10:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/dark.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>These days, lots of developers like to use dark mode. And it's no surprise, as activating dark mode reduces eye strain and leads to better eye health. It also helps both machines and humans perform better overall.</p>
<p>In this article, I will show you how to turn on the dark theme on your Google Chrome app, on both Windows machines and Android phones. We'll also learn how to turn on dark theme for Google with some Chrome extensions. </p>
<p>It doesn’t end there – you will also be able to run your Windows apps in dark mode after reading this article.</p>
<h2 id="heading-how-to-turn-on-dark-mode-for-google-on-windows-10">How to Turn on Dark Mode for Google on Windows 10</h2>
<p><strong>Step 1</strong>: To turn on dark theme for Google on your Windows 10 PC, click on Start, or press the <code>WIN</code> (Windows) key.</p>
<p><strong>Step 2</strong>: Click on Settings
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-1.jpg" alt="ss-1" width="600" height="400" loading="lazy"></p>
<p><strong>Step 3</strong>: Click on Personalization
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-2.jpg" alt="ss-2" width="600" height="400" loading="lazy"></p>
<p><strong>Step 4</strong>: Select Colors from the menu tab
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-3.jpg" alt="ss-3" width="600" height="400" loading="lazy"></p>
<p><strong>Step 5</strong>: And finally, under “Choose your default app mode”, choose dark.
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-4.jpg" alt="ss-4" width="600" height="400" loading="lazy"></p>
<p>The settings app itself will change to dark mode, meaning all the apps on your machine are now running on dark mode.
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-5-1.png" alt="ss-5-1" width="600" height="400" loading="lazy"></p>
<p>To confirm that Google is now running on dark mode, open up the Chrome app and search anything on Google:
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-6.png" alt="ss-6" width="600" height="400" loading="lazy"></p>
<p>Other parts of Chrome will run on dark theme, too:
<img src="https://www.freecodecamp.org/news/content/images/2021/10/other-parts-of-chrome.png" alt="other-parts-of-chrome" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-turn-on-dark-mode-for-google-with-a-chrome-extension">How to Turn on Dark Mode for Google With a Chrome Extension</h2>
<p>To turn on dark theme for Google with a Chrome extension, download and activate the Just Black chrome extension from the Chrome Web Store. </p>
<p>The extension was built by the Chrome team, so it's safe to install and use.
<img src="https://www.freecodecamp.org/news/content/images/2021/10/just-black.png" alt="just-black" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-turn-on-dark-mode-for-google-on-android-phones">How to Turn on Dark Mode for Google on Android Phones</h2>
<p><strong>Step 1</strong>: To turn on dark mode for Google on an Android phone, open your chrome app and click on the three dots in the top right corner.
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-a1.jpg" alt="ss-a1" width="600" height="400" loading="lazy"></p>
<p><strong>Step 2</strong>: Tap settings
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-a2.jpg" alt="ss-a2" width="600" height="400" loading="lazy"></p>
<p><strong>Step 3</strong>: Select theme
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-a3.jpg" alt="ss-a3" width="600" height="400" loading="lazy"></p>
<p><strong>Step 4</strong>: Finally, choose dark
<img src="https://www.freecodecamp.org/news/content/images/2021/10/ss-a4.jpg" alt="ss-a4" width="600" height="400" loading="lazy"></p>
<p>Your Chrome mobile app should be in dark mode, including the Google search page:
<img src="https://www.freecodecamp.org/news/content/images/2021/10/Screenshot_20211008-163435.png" alt="Screenshot_20211008-163435" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to turn on dark mode for Google on Windows machines and Android phones. </p>
<p>You also learned how to do the same with a chrome extension. </p>
<p>There are several other extensions that give you dark mode on Chrome, so feel free to check them out on the Chrome Web Store.</p>
<p>Thank you for reading, and have a nice time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Gmail Dark Mode – How to Change the Gmail Background Theme on Desktop, iOS, and Android ]]>
                </title>
                <description>
                    <![CDATA[ If you're like me, you spend several hours a week in Gmail. Staring at Gmail's bright white design can strain your eyes – especially at night. Fortunately, Gmail has a built-in dark mode theme. This will make it much easier to read at night. In addit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/gmail-dark-mode/</link>
                <guid isPermaLink="false">66ac87f54465950a6e26c92f</guid>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ gmail ]]>
                    </category>
                
                    <category>
                        <![CDATA[ how-to ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kristofer Koishigawa ]]>
                </dc:creator>
                <pubDate>Thu, 08 Apr 2021 06:07:32 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/602b5ce90a2838549dcc632e.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're like me, you spend several hours a week in Gmail. Staring at Gmail's bright white design can strain your eyes – especially at night.</p>
<p>Fortunately, Gmail has a built-in dark mode theme. This will make it much easier to read at night.</p>
<p>In addition to reducing eye strain, dark mode can even reduce the battery consumption of your device, allowing you to use it for longer without charging it. (It's a small improvement, but it helps.)</p>
<p>So how do you turn on dark mode in Gmail? I'll show you how to switch to Gmail's dark theme in just a few steps.</p>
<h2 id="heading-gmail-dark-mode-on-desktop">Gmail Dark Mode on Desktop</h2>
<p>First, open your browser and go to <a target="_blank" href="https://mail.google.com/">Gmail</a>. Sign in if necessary.</p>
<p>Click on the gear icon in the top right and next to "Theme" click "View all":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-browser-1-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the "Pick your theme" menu, scroll down until you see the different color options.</p>
<p>Select "Dark" (this text will be visible when you hover over the black thumbnail), and click "Save":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-browser-2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And when you go back to your inbox, it'll be in dark mode:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-browser-final.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-gmail-dark-mode-on-android">Gmail Dark Mode on Android</h2>
<p><strong>Note:</strong> This method requires Android 10 and up.</p>
<p>First, open the <a target="_blank" href="https://play.google.com/store/apps/details?id=com.google.android.gm">Gmail</a> app. Download the app and / or sign in if necessary.</p>
<p>In Gmail, open the side menu by tapping the three vertical bars on the top left of the screen, or by swiping from the left:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-1-5.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the side menu, scroll down to the bottom and tap "Settings":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then in the Settings menu, tap "General settings":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-3.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the General settings menu, tap "Theme":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-4.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finally in the Theme pop up menu, select "Dark":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-5.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And Gmail will switch to dark mode:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-android-final-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-gmail-dark-mode-on-ios">Gmail Dark Mode on iOS</h2>
<p><strong>Note:</strong> This method requires iOS 13 and up.</p>
<p>If you have an iPhone and want your Gmail to be in dark mode, it's super simple to make that happen.</p>
<p>There isn't a setting in the Gmail app itself – you simply set your phone's settings to dark mode (and Gmail will follow suit). Here's how to do that.</p>
<p>First, go to your phone's "Settings" and scroll until you see "Display &amp; Brightness" partway down:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/iphone-settings.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on Display and Brightness, and you'll be taken to this screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-vs-light-mode.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, my phone is currently set to Light Mode (it's selected). If I want to switch to dark mode,  just toggle that option on, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/change-to-dark-mode.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now my phone is set to dark mode (all the time, rather than just auto-adjusting when it gets dark outside).</p>
<p>So my Gmail app will now look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-gmail.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There you have it! If you only want your Gmail app to use dark mode at night, you can update your settings accordingly. </p>
<p>Just make sure your phone is on Light mode and the "Automatic" option is toggled on. Then just select the "Sunset to Sunrise" option under "Options" and your phone will automatically adjust your apps into dark mode when the sun goes down!</p>
<p>It'll look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/dark-mode-vs-light-mode-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-thanks-for-reading"><strong>Thanks for Reading</strong></h2>
<p>If you found this helpful, please share it with your friends so more people can enable Gmail's dark mode on desktop, Android, and iOS devices.</p>
<p>Also, if you liked this article, let me know over on <a target="_blank" href="https://twitter.com/kriskoishigawa">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Enable Dark Mode in HTML Email – Everything You Need to Know ]]>
                </title>
                <description>
                    <![CDATA[ By Patrik Krupař With the new iOS 13 update, Apple Mail is getting a dark theme. That means it's the first major email client that supports the prefers-color-scheme CSS media query. So you can now design emails specifically for both dark and light th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dark-mode-in-html-email-everything-you-need-to-know/</link>
                <guid isPermaLink="false">66d4608ca326133d12440a53</guid>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ email ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 16 Dec 2019 12:20:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/iPhone-X-XS---7@2x.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Patrik Krupař</p>
<p>With the new iOS 13 update, Apple Mail is getting a dark theme. That means it's the first major email client that supports the <code>prefers-color-scheme</code> CSS media query. So you can now design emails specifically for both dark and light themes.</p>
<p>I’m a massive dark mode fan, and blindingly-bright email is my nemesis. So when I learned about dark mode in iOS 13, I did the only obvious thing and ordered a brand new iPhone to test things out.</p>
<p>While I was at it, I also tested how dark mode works in almost all email clients, including the troublemaker Outlook. Here’s what I found.</p>
<p><strong>But first, w</strong>hat is prefers-color-scheme?<em>**</em><br>The <code>prefers-color-scheme</code> CSS media query is used to detect whether the user prefers a light or dark theme, making it possible to design email specifically for both. </p>
<p>With the iOS 13 update, <strong>the support in most popular email clients jumped from 2.3% to 38.4%</strong>! A huge step thanks to Apple Mail's popularity. Surprisingly, Outlook was the only email client that supported this before Apple Mail.</p>
<h2 id="heading-how-dark-mode-works-in-popular-email-clients">How dark mode works in popular email clients</h2>
<p>To render the email message dark itself, email clients invert the email’s colors automatically behind the scenes. For regular user-to-user emails, this works well and consistently in all email clients.</p>
<p>However, it’s not that simple for custom HTML emails — those that fill most of our inboxes. I’m talking transactional and promotional.</p>
<p>Here’re the differences I found in how email clients handle dark mode email rendering:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Email client</td><td>Popularity</td><td>Dark UI</td><td>Auto-invert email colors</td><td>Supports @media (prefers-color-scheme)</td><td></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Apple Mail</strong> iPhone + iPad</td><td>36.1%</td><td>✔&nbsp;Yes</td><td>✔&nbsp;Yes</td><td>✔&nbsp;Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/applemail-ios.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Gmail</strong> Android 10</td><td>27.8% *</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/gmail-android-1.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Gmail</strong> iOS 13</td><td>27.8% *</td><td>✖ No</td><td>✖ No</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/gmail-ios.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Gmail</strong> webmail</td><td>27.8% *</td><td>✔ Yes</td><td>✖ No</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/gmail-webmail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Outlook</strong> iOS 13</td><td>9.1% *</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/outlook-ios.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Outlook</strong> Android 10</td><td>9.1% *</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/outlook-android-1.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Outlook</strong> Windows 10</td><td>9.1% *</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/outlook-windows-10.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Outlook</strong> macOS</td><td>9.1% *</td><td>✔ Yes</td><td>✔ Yes</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/outlook-macos.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Apple Mail</strong> macOS</td><td>7.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/applemail-macos.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Yahoo!</strong> webmail</td><td>6.3% *</td><td>✔ Yes</td><td>✖ No</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/yahoo-webmail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>AOL</strong> webmail</td><td>6.3% *</td><td>✖ No</td><td>✖ No</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/aol-webmail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Outlook.com</strong> webmail</td><td>2.3%</td><td>✔ Yes</td><td>✔ Yes</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/outlook-webmail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Windows 10 Mail</strong> Windows 10</td><td>0.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/windows-10-mail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Zoho Mail</strong> webmail</td><td>less than 0.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✖ No</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/zoho-webmail.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Mozilla Thunderbird</strong> Windows 10</td><td>less than 0.5%</td><td>✔ Yes</td><td>✖ No</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/thunderbird-windows-10.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Spark</strong> macOS</td><td>less than 0.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/spark-macos-dark-mode.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Spark</strong> iOS 13</td><td>less than 0.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/spark-ios-dark-mode.png">(Show screenshot)</a></td></tr>
<tr>
<td><strong>Spark</strong> Android 9</td><td>less than 0.5%</td><td>✔ Yes</td><td>✔ Yes</td><td>✔ Yes</td><td><a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/spark-android-dark-mode.png">(Show screenshot)</a></td></tr>
</tbody>
</table>
</div><p><em>* Popularity is shared across all platforms for the same email client because it cannot be reliably distinguished. Popularity source:</em> <a target="_blank" href="https://litmus.com/blog/infographic-the-2019-email-client-market-share"><em>Litmus, the 2019 email client market share</em></a><em>.</em></p>
<p>(<a target="_blank" href="https://sidemail.io/articles/dark-mode-in-html-email/">Visit the original post</a> to view my notes from the testing, and to see the latest tests as I gradually test more email clients and update the article there first.)</p>
<h2 id="heading-how-to-make-html-emails-dark-mode-friendly">How to make HTML emails dark mode friendly</h2>
<p>I already put the data to use, and a few Outlook related challenges later, I made our emails dark mode friendly. <strong>Here’s how you can do the same:</strong></p>
<blockquote>
<p><strong>What the data say:</strong><br>More than 55% of emails might be opened with dark mode enabled. Once Gmail joins the dark side, emails that might be opened with dark mode enabled will skyrocket to 83%!</p>
</blockquote>
<h3 id="heading-1-adjusting-colors">1) Adjusting colors</h3>
<p>Look out for Apple Mail, as it inverts colors only if the background color is transparent or unspecified — <strong>white background won’t do</strong>. The easiest way to make sure your emails won’t blind anybody is to check whether a background color is specified. For more control over the design, this is where <code>prefers-color-scheme</code> comes in handy.</p>
<p><strong>Syntax (@media prefers-color-scheme):</strong></p>
<pre><code class="lang-css">&lt;<span class="hljs-selector-tag">style</span>&gt;
    <span class="hljs-comment">/* Your light mode (default) styles: */</span>
    <span class="hljs-selector-tag">body</span> {
        <span class="hljs-attribute">background</span>: white;
        <span class="hljs-attribute">color</span>: <span class="hljs-number">#393939</span>;
    }

    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">prefers-color-scheme:</span> dark) {
        <span class="hljs-comment">/* Your dark mode styles: */</span>

        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">background</span>: black;
            <span class="hljs-attribute">color</span>: <span class="hljs-number">#ccc</span>;
        }
    }
&lt;/<span class="hljs-selector-tag">style</span>&gt;
</code></pre>
<p><strong>A design tip:</strong> Avoid pure white <code>#fff</code> as the text color. I found that contrast ratio around 11.5 for the main text is a nice compromise between not too bright and not too dim. Check the contrast ratio here: <a target="_blank" href="https://contrast-ratio.com/">https://contrast-ratio.com</a> or use Chrome dev tools.</p>
<p><img src="https://sidemail.io/static/switching-logo-ccb909c2e5c3de55aeb36e5e69ca4d8b.svg" alt="Switching between light and dark logo version in HTML email with prefers-color-scheme media query" width="600" height="400" loading="lazy"></p>
<h3 id="heading-2-switching-between-light-and-dark-logo">2) Switching between light and dark logo</h3>
<p>A dark text on a dark background is pretty much invisible, and that’s precisely what happens to a logo if viewed in an email client with enabled dark mode.</p>
<p>Nowadays, a typical logo usually has a transparent background, colorful icon, and dark copy. See the problem? Because email clients don’t invert image colors, you need to handle it yourself.</p>
<p>To tackle this, you can either:</p>
<ol>
<li>save the logo with a white background instead of a transparent background (the easiest way to fix this). But I wouldn’t recommend this approach — dark mode users won’t be happy.</li>
<li>put a light logo on a dark background, and keep the rest of the email on a white background (<a target="_blank" href="https://sidemail.io/assets/dark-mode-in-html-email/litmus-light-logo-on-dark-background.png">see how Litmus does it</a>).</li>
<li>make dark mode email your default. A good candidate for this would be Spotify as they only offer a dark theme in their apps.</li>
<li>include both light and dark versions of your logo and switch between with <code>prefers-color-scheme</code> media query</li>
</ol>
<p>My favorite is the last approach, so here’s how you do it:</p>
<p>A simple <code>"display: none"</code> on the dark logo works just fine in all modern email clients. But to everyone's surprise, it doesn't work in Outlook and Windows 10 Mail.</p>
<p>In CSS styles:</p>
<pre><code class="lang-css">&lt;<span class="hljs-selector-tag">style</span>&gt;
    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">prefers-color-scheme:</span> dark) {
        <span class="hljs-selector-class">.darkLogo</span> {
            <span class="hljs-attribute">display</span>: none <span class="hljs-meta">!important</span>;
        }

        <span class="hljs-selector-class">.lightLogoWrapper</span>,
        <span class="hljs-selector-class">.lightLogo</span> {
            <span class="hljs-attribute">display</span>: block <span class="hljs-meta">!important</span>;
        }
    }
&lt;/<span class="hljs-selector-tag">style</span>&gt;
</code></pre>
<p>…and the HTML structure:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"dark-logo.png"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"darkLogo"</span> /&gt;</span>

<span class="hljs-comment">&lt;!--
    To hide the light logo perfectly in Outlook and Windows 10 Mail, 
    you need to wrap the light logo image tag with a div.
--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lightLogoWrapper"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"mso-hide: all; display: none"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"light-logo.png"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lightLogo"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display: none"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>This approach works pretty well, but it still won’t work correctly across the board. The dark text on dark background issue will happen with email clients that do support dark mode but don't support <code>prefers-color-scheme</code>. That is Outlook, Windows 10 Mail, Zoho, and potentially Gmail.</p>
<p><img src="https://sidemail.io/static/switching-logo-bulletproof-00ecb22b52186ddbf8bf6deec5c9b9f5.svg" alt="Bulletproof method: switching between light and dark logo version in HTML email with prefers-color-scheme media query" width="600" height="400" loading="lazy"></p>
<p>So, to make the logo in email fully bulletproof, I’ll combine methods 1 and 4 from above. Method 1 will cover all email clients that support dark mode, but not the <code>prefers-color-scheme</code>. And method 4 will cover Apple Mail, Outlook on MacOS, and Outlook.com, which does support both.</p>
<p>Also, instead of saving the logo on a white background, I’ll add a 3-pixel wide background-matching border and save it on a transparent background as usual.</p>
<p>It’s starting look pretty complex (just for a logo), so let’s see the HTML markup first:</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Default logo with 3-pixel wide background-matching border --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"dark-logo-with-background.png"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"darkLogoDefault"</span> /&gt;</span>

<span class="hljs-comment">&lt;!-- Light theme (so dark logo): 
This is for Apple Mail, Outlook on macOS, Outlook.com --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"darkLogoWrapper"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"mso-hide: all; display: none"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"dark-logo.png"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"darkLogo"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display: none"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Dark theme (so light logo): 
This is for Apple Mail, Outlook on macOS, Outlook.com --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lightLogoWrapper"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"mso-hide: all; display: none"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"light-logo.png"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lightLogo"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display: none"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>…and CSS styles:</p>
<pre><code class="lang-css">&lt;<span class="hljs-selector-tag">style</span>&gt;
    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">prefers-color-scheme:</span> light) {
        <span class="hljs-selector-class">.darkLogoDefault</span>,
        <span class="hljs-selector-class">.lightLogo</span> {
            <span class="hljs-attribute">display</span>: none <span class="hljs-meta">!important</span>;
        }

        <span class="hljs-selector-class">.darkLogoWrapper</span>,
        <span class="hljs-selector-class">.darkLogo</span> {
            <span class="hljs-attribute">display</span>: block <span class="hljs-meta">!important</span>;
        }
    }

    <span class="hljs-keyword">@media</span> (<span class="hljs-attribute">prefers-color-scheme:</span> dark) {
        <span class="hljs-selector-class">.darkLogoDefault</span>,
        <span class="hljs-selector-class">.darkLogo</span> {
            <span class="hljs-attribute">display</span>: none <span class="hljs-meta">!important</span>;
        }

        <span class="hljs-selector-class">.lightLogoWrapper</span>,
        <span class="hljs-selector-class">.lightLogo</span> {
            <span class="hljs-attribute">display</span>: block <span class="hljs-meta">!important</span>;
        }
    }
&lt;/<span class="hljs-selector-tag">style</span>&gt;
</code></pre>
<h2 id="heading-dark-mode-in-gmail-is-coming">Dark mode in Gmail is coming</h2>
<p>Dark mode is coming to Android in the new Android 10, and Gmail should go completely dark too, finally. All you need is Android 10 and the newest Gmail (at least version 2019.09.01.268168002). However, Google tends to enable new features (a dark theme in this case) for users gradually with a server-side push, and I haven’t had luck with it for now.</p>
<p>I’m curious to see if support for <code>@media prefers-color-scheme</code> is coming to Gmail. From what I read, it doesn’t seem promising. I guess we have to wait to find out. I’ll update the article once I get the dark theme in Gmail enabled.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Dark mode is coming to HTML email, and I love it! But, it’s another thing to worry about – like using HTML tables for layout wasn’t enough.</p>
<p><a target="_blank" href="https://hosted.sidemail.io/5d919d2fcc34a000fc97cfed">Stay up-to-date about the dark mode in email by joining our mailing list</a>. We also share there insights and challenges we face while building and growing our SaaS product — <a target="_blank" href="https://sidemail.io/">Sidemail</a>.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How I added Dark Mode to my website ]]>
                </title>
                <description>
                    <![CDATA[ I recently redesigned my website. Here are 2 pictures of how it looked, for reference: I designed this website almost 1 year ago, and did many changes along the way, just as we do with any website. Eventually I grew tired of the design: title is to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-i-added-dark-mode-to-my-website-33611d246425/</link>
                <guid isPermaLink="false">66bb5a6e24dd38751ddeb5cf</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ UX ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Flavio Copes ]]>
                </dc:creator>
                <pubDate>Mon, 04 Feb 2019 15:42:31 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*izsJBvK2z3sNZvkh.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I recently redesigned <a target="_blank" href="https://flaviocopes.com">my website</a>. Here are 2 pictures of how it <em>looked</em>, for reference:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/omFzYPaJhb-CmAV7a0zLCSz00Ac31sfbUeV4" alt="Image" width="800" height="880" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/roWIFwsXoad3bhcoXrEUXVLarbvX9UB2vbgQ" alt="Image" width="800" height="880" loading="lazy"></p>
<p>I designed this website almost 1 year ago, and did many changes along the way, just as we do with any website.</p>
<p>Eventually I grew tired of the design: title is too big, too much space lost instead of showing the content right away, and so on.</p>
<p>I sat down yesterday evening and started re-imagining the website, and I finished the redesign this morning:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/WJZ6y3YnXqUNhJ4Ceav4LAAd5jFDc63TmQNw" alt="Image" width="800" height="880" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AwAm1Tjr6abfHw5kPGo-9QGoIweVIOJr4oI5" alt="Image" width="800" height="880" loading="lazy"></p>
<p>Much better! Content, the most important thing, is more prominent.</p>
<p>I used a monospaced font (Inconsolata) because as a programming blog it’s a nice one, despite the reduced readability and increased page size due to the font use, because I <em>want</em> that font on my site. I like it better, and since my site is a big part of my day to day activity, I wanted it to be what I want.</p>
<p>I just missed one thing: <strong>dark mode</strong>. As I was in the process of redesigning, I had the dark mode option in mind.</p>
<p>How did I do it? First, I added the Moon Emoji ? in the sidebar, as a way to let people change the mode from light to dark.</p>
<p>Then, I added a JavaScript snippet that runs when it’s clicked. I just added it to the <code>onclick</code> event handler inline in the HTML, without going fancier:</p>
<pre><code>&lt;p&gt;  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"localStorage.setItem('mode', (localStorage.getItem('mode') || 'dark') === 'dark' ? 'light' : 'dark'); localStorage.getItem('mode') === 'dark' ? document.querySelector('body').classList.add('dark') : document.querySelector('body').classList.remove('dark')"</span> <span class="hljs-attr">title</span>=<span class="hljs-string">"Dark/light&lt;/p&gt;</span></span></span>
</code></pre><p>This is the JavaScript that runs in the onclick:</p>
<pre><code><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'mode'</span>, (<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'mode'</span>) || <span class="hljs-string">'dark'</span>) === <span class="hljs-string">'dark'</span> ? <span class="hljs-string">'light'</span> : <span class="hljs-string">'dark'</span>); <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'mode'</span>) === <span class="hljs-string">'dark'</span> ? <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>).classList.add(<span class="hljs-string">'dark'</span>) : <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>).classList.remove(<span class="hljs-string">'dark'</span>)
</code></pre><p>It’s a bit convoluted, but basically I check if the <code>mode</code> property in the <a target="_blank" href="https://flaviocopes.com/web-storage-api/">local storage</a> is ‘dark’ (and defaults to dark if it’s not set yet, using the <code>||</code> operator), and I set the opposite of that in the local storage.</p>
<p>Then I assign the <code>dark</code> class to the <code>body</code> HTML element, so we can use CSS to style the page in dark mode.</p>
<p>Another script runs as soon as the DOM loads, and checks if the mode is dark. If so, it adds the <code>dark</code> class to the <code>body</code> HTML element:</p>
<pre><code><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {  ((<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'mode'</span>) || <span class="hljs-string">'dark'</span>) === <span class="hljs-string">'dark'</span>) ? <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>).classList.add(<span class="hljs-string">'dark'</span>) : <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>).classList.remove(<span class="hljs-string">'dark'</span>)})
</code></pre><p>Now if people change modes, their choice will be remembered next time they load the page.</p>
<p>Then I added a lot of CSS instructions to the CSS, all prefixed with <code>body.dark</code>. Like these:</p>
<pre><code>body.dark {  background-color: rgb(<span class="hljs-number">30</span>,<span class="hljs-number">34</span>,<span class="hljs-number">39</span>);  color: #fff;}body.dark code[<span class="hljs-class"><span class="hljs-keyword">class</span>*</span>=language-],body.dark table tbody&gt;tr:nth-child(odd)&gt;td,body.dark table tbody&gt;tr:nth-child(odd)&gt;th {  <span class="hljs-attr">background</span>: #<span class="hljs-number">282</span>c34}
</code></pre><p>Now things should already be working! Here is my site in dark mode:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qLGFEyXtuhIuhkoxWZUHeMxsO979cAzAyZwG" alt="Image" width="800" height="880" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/fopjlWMiRnntpt8x-k6DlWrzZKHagsSftcRT" alt="Image" width="800" height="880" loading="lazy"></p>
<p>I added the <code>dark</code> class to the <code>body</code> element by default, to make dark mode the default:</p>
<pre><code>&lt;body <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"dark"</span>&gt; ... &amp;lt;/body&gt;
</code></pre><p>Why? First, I liked it better. Then, I made a poll on Twitter and people liked it better.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/gl9vci-v5yBlwHtnVsqkgn8EhphopCHUeTY3" alt="Image" width="626" height="191" loading="lazy"></p>
<p>But also for a technical reason, a very simple one actually. I don’t store the user choice server-side, so I have no way to know the mode until the local storage is available.</p>
<p>I could do that if the site was generated server-side, but it’s a static site, so I always serve the same page to everyone that requests it. Even if I got a cookie, I have no place to process it (on the flip side this means my pages load faster).</p>
<p>So when someone navigates to another page on my site, or loads the page for the first time on a second visit, I don’t want to show a bright page while I determine the mode. Maybe the visitor is coding in the middle of the night in a dark room.</p>
<p>I’d rather do that in light mode: show a dark page for a couple milliseconds and then turn it white again.</p>
<p>The <em>Media Queries Level 5</em> specification, still in work in progress, contains a new <code>[prefers-color-scheme](https://drafts.csswg.org/mediaqueries-5/#prefers-color-scheme)</code> media feature. <a target="_blank" href="https://developer.apple.com/safari/technology-preview/">Safari Technology Preview</a> on macOS already supports it and we can use it to tell if the user is browsing the page in dark or light mode:</p>
<pre><code>@media (prefers-color-scheme: dark) {  body {    background-color: black;    color: white;  }}@media (prefers-color-scheme: light) {  body {    background-color: white;    color: black;  }}
</code></pre><p>Hopefully this is going to be stable in Safari soon, and in the future Chrome and Firefox will support it too.</p>
<p><em>Originally published at <a target="_blank" href="https://flaviocopes.com/dark-mode/">flaviocopes.com</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
