2

I'm building a PWA for iOS and Android, and I'm not using a framework (it is a very basic app and app size is a big issue). I want to implement dark mode so that when the user switches their device to dark mode, the app theme changes dark too. How do I do this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jamie W
  • 439
  • 3
  • 21

1 Answers1

3

I’ve been stuck on this for a while now and I think I’ve come across a good solution. Previously I’ve used the ionic 4 framework and their Docs contain an interesting page about adding dark mode to a PWA. Link here

It talks about a CSS selector that can detect when the user’s device is running on dark mode, and change the element styles accordingly. From the docs:

The first way to enable dark mode is by using the CSS media query for the user's preferred color scheme. This media query will hook into the system setting of the user's device and apply the theme if a dark mode is enabled.

@media (prefers-color-scheme: dark) {
  :root {
    /* dark mode variables go here */
  }
}

Currently, the prefers-color-scheme media query has limited browser support, so users will not be able to benefit from having the dark mode applied using this media query in certain browsers. However, the dark mode can still be applied by using a CSS class fallback.

/* Fallback for older browsers or manual mode */
body.dark {
  /* Dark mode variables go here */
}

I’ve tested this in my PWA on iOS 13 and iPadOS, and they both seem to work when I change my device to dark mode. I’m not sure about android but I expect the result will be the same.

It’s also worth noting that you can enable your app’s dark mode settings though the app (ie. have a setting within your app, so your app can be dark even when the device isn’t). The demo further down the docs page demonstrates this nicely.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jamie W
  • 439
  • 3
  • 21