Enabling dark and light mode in a website

Enabling dark and light mode is common for website and applications these days, and its easier than ever to support this by simply using css and javascript.

This website will adjust to the settings of your OS. This can be done easily and I will you show. Try toggling between dark and light mode in your OS and see how the website will adjust accordingly.

Using CSS variables

CSS variables let's you define variables that you can make use of in your css files. Let's say we want to set our main background color like this.

:root {
  --main-bg-color: brown;
}

Then we can make use of this variable in other parts of our codebase like this.

body {
  background-color: var(--main-bg-color);
}

You can do the same for any css properties you need, for instance text colors, font sizes, border radius, shadows etc. Its a great way of keeping your UI consistent by re-using similar font-sizes, widths, height, radius etc.

To adjust the settings according to the OS settings, you can do to the following.

@media (prefers-color-scheme: light) {
  :root {
    --primary-bg-color: #fff;
    --primary-text-color: #000000d7;
    --secondary-text-color: #535252;
    --primary-link-color: #0070f3;
    --image-grayscale: 0;
    --image-opacity: 100%;
  }
}

@media (prefers-color-scheme: dark) {
  :root {
    --primary-bg-color: rgb(45, 51, 59);
    --primary-text-color: rgb(205, 217, 229);
    --secondary-text-color: rgb(168, 177, 186);
    --primary-link-color: #79b7ff;
    --image-grayscale: 0;
    --image-opacity: 100%;
  }
}

This will set the root variables depending on which prefered color scheme the user has in their OS.

Using Javascript

With javascript you can change these settings.

Change a variable:

element.style.setProperty('--main-bg-color', 'blue');

To read a value:

getComputedStyle(window.document.body).getPropertyValue('--main-bg-color');

Its as easy as that.

← Back to home