Add Dark Mode to Website in 3 Steps with CSS

How to add dark mode to website
Add dark mode to your website with 3 easy steps using CSS. Adding prefers-color-scheme is easy, although there are fine details to solve for.

This website features a dark mode and a light mode appearance. Which mode you see depends on the appearance setting that you have on your particular device.

Fisnik Deshishku Dark Mode Website

 
Ever since dark mode has been introduced to macOS with the Mojave update there has been waves of hype around it. Dark mode really started to pickup popularity when iOS 13 released just 1 year after the macOS Mojave update. The ability to transition from light to dark mode automatically based on a set schedule enhances visual ergonomics by reducing eye strain and providing comfort while using the device at night.

In this post you will learn how to add the dark mode compatibility with CSS to your personal website that changes automatically based on the user device setting.

Step 1: Add media query ‘prefers-color-scheme’ feature

@media (prefers-color-scheme: dark) {

/* custom css */

}

Step 2: Light text on dark background

One of the most important blocks is the one that overrides the background color and text color.

body {
  background-color: #1c1c1e;
  color: #fefefe;
}

To prevent text from really popping out and to give it a more subtle appearance when in dark mode, it is recommended to avoid pure white for text; Likewise, I personally chose to also avoid using pure black for the background.

Step 3: Desaturate colors

The accent colors used for hyperlinks on a white background may appear brighter on a dark background depending on the color you’re currently using. If that is the case, desaturate the original color to a less saturated one.

a {
  color: #5fa9ee;
}

Images also tend to appear more vivid and based on a recent survey from Thomas Steiner, majority of people voted to desaturate images in dark mode.

img {
  filter: grayscale(20%);
}

Regarding certain icons or vector images, you may need to invert their color.

Final code:

@media (prefers-color-scheme: dark) {
  body {
    background-color: #1c1c1e;
    color: #fefefe;
  }
  a {
    color: #5fa9ee;
  }
  img {
    filter: grayscale(20%);
  }
}

NOTE: This approach changes the main components, but not all. Depending on your theme style, there will be various class/id styles that you will also need to modify within the “@media (prefers-color-scheme: dark)” to fully change everything from light to dark mode.

Scroll to Top