Skip to content

Prefer ‘prefers-color-scheme‘ but allow it to be overridden by the user #2959

Closed Answered by simonswiss
SSmale asked this question in Help
Discussion options

You must be logged in to vote

Hey! 👋

A possible implementation of this is presented in the Tailwind CSS docs website:

// On page load or when changing themes, best to add inline in `head` to avoid FOUC
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
  document.querySelector('html').classList.add('dark')
} else {
  document.querySelector('html').classList.remove('dark')
}

// Whenever the user explicitly chooses light mode
localStorage.theme = 'light'

// Whenever the user explicitly chooses dark mode
localStorage.theme = 'dark'

// Whenever the user explicitly chooses to respect the OS preference
localStorage.removeItem('theme')

Is that …

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by simonswiss
Comment options

You must be logged in to vote
1 reply
@simonswiss
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants