DEV Community

yogeshwaran
yogeshwaran

Posted on • Originally published at yogeshwaran.in on

Media query for dark mode in css

Dark mode css

Its 2021 almost every android,ios and windows devices have the option to choose light/dark mode as their preferable mode. its nice to have dark/light mode in your websites. Fancy isn't it ?

Media query for Dark mode

@media (prefers-color-scheme: dark) {
}
Enter fullscreen mode Exit fullscreen mode

if your website theme is already have dark backrounds and light text. you can do it in reverse by adding light mode media query.

Media query for Light mode

@media (prefers-color-scheme: light) {
}
Enter fullscreen mode Exit fullscreen mode

If you are not using css variables or any preprocessors in your website. you need to overwrite most of the color for having it in dark/light mode.

CSS Variables are handy

Using css variables it is easy to setup colors for dark/light mode in a simple way by replacing color variables in media query

:root {
  --background: #fff;
  --text-color: #323232;
}

// Dark mode
@media (prefers-color-scheme: dark) {
  :root {
    --background: #323232;
    --text-color: #fff;
  }
}
Enter fullscreen mode Exit fullscreen mode

Live example

Try switching dark and light mode in your device and see how the below page renders

See the Pen Media query for dark mode by yogeshwaran
(@yoyo) on CodePen.

Feel free to ask me in case of doubts. i am very much happy to help you.

Top comments (0)