I am Barry Hess

Dark mode colors with CSS variables

I have been working on simplifying the design of my site. I wanted a design that was easy to maintain, adjusts to the screen on which you are reading, and was very readable across screen lighting modes. When I started looking for ways to simply change CSS depending on whether the reader was viewing in a light or dark mode on their device, I was surprised to find search result after search result offering solutions using CSS classes swapped in and out with JavaScript. This didn’t feel like a problem that needed to be solved with JavaScript!

I started playing around with CSS custom properties. In the simplest terms, these work as variables that can be defined in one place and changed in one place, but referenced throughout your CSS files. Seems like a great option to adjust the value of background colors when dark mode is detected!

To detect dark mode I needed the media query prefers-color-scheme. This sort of thing can be placed at the top of a CSS file (or in a separate file that you @import) and the variables can be freely used throughout the rest of your CSS code:

:root {
  --main-bg-color: #96BFE6;  /* Salvia Blue */
  --secondary-bg-color: #f0f8ff;  /* Light Blue */
  --text-color: #651300;  /* Madder Brown */
  --secondary-text-color: #551000;  /* Madder Brown - Dark */

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: #121212;  /* Blackish */
    --secondary-bg-color: #1F1B24;  /* Purple-Blackish */
    --text-color: #eee;  /* You know */
    --secondary-text-color: #ddd;  /* Yeah */

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

.portfolio {
  background-color: var(--secondary-bg-color);
  color: var(--secondary-text-color);

As more varying design colors are brought into the design and used multiple times throughout the rest of the CSS, centralizing the color elements in one spot will be very helpful for colorizing in both light and dark modes. I hope this helps someone out there!

Note: I assume all the examples I found use JavaScript because there probably is some worry about browser compatibility for prefers-color-scheme. In my case I’m not concerned about seeing the same behavior in browsers that are not recognizing this useful media query. I guess their screens will remain bright in the dark!