Theme Hacks

Adding Dark Mode to Shopify Themes

By Mohd Baquir Qureshi
Dark Mode UI

Providing a dark mode option on your Shopify store is no longer just a gimmick. Users actively seek out dark themes, particularly for evening browsing, and it can help reduce eye strain and prolong battery life on OLED devices. The good news is that with modern CSS Variables, adding dark mode to a Shopify Dawn theme is surprisingly straightforward.

1. Setting Up CSS Variables (Custom Properties)

The foundation of any good dark mode implementation relies on CSS variables. If your theme hardcodes colors like #FFFFFF directly into component styles, you'll have a nightmare trying to override them. Instead, open your base.css or theme.css and define your core colors at the root.

:root {
  --color-background: #ffffff;
  --color-text: #1a1a1a;
  --color-button: #000000;
  --color-button-text: #ffffff;
  --color-border: #e2e8f0;
}

/* Define the Dark Mode overrides */
[data-theme="dark"] {
  --color-background: #121212;
  --color-text: #e0e0e0;
  --color-button: #ffffff;
  --color-button-text: #000000;
  --color-border: #333333;
}

2. Implementing the JavaScript Toggle

We need a way for users to manually toggle the theme, while also respecting their operating system's default preference. We'll use localStorage to remember their choice across page loads.

const themeToggle = document.getElementById('theme-toggle');
const currentTheme = localStorage.getItem('theme');

// Check user preference or system preference
if (currentTheme === 'dark' || (!currentTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
  document.documentElement.setAttribute('data-theme', 'dark');
}

// Add event listener to the toggle button
themeToggle.addEventListener('click', () => {
  let theme = document.documentElement.getAttribute('data-theme');
  if (theme === 'dark') {
    document.documentElement.removeAttribute('data-theme');
    localStorage.setItem('theme', 'light');
  } else {
    document.documentElement.setAttribute('data-theme', 'dark');
    localStorage.setItem('theme', 'dark');
  }
});

3. Handling Images and SVGs

Text and backgrounds are easy, but bright images can be jarring on a dark background. A neat trick is to slightly decrease the brightness and increase the contrast of images when dark mode is active.

[data-theme="dark"] img {
  filter: brightness(0.8) contrast(1.2);
}

Conclusion

By leveraging CSS variables and a tiny bit of JavaScript, you can implement a robust dark mode toggle that respects user preferences and improves the overall shopping experience without adding heavy third-party apps to your store.