Enabling Dark Mode in CSS

Using the prefers-color-scheme css media query to darken pages depending on system preferences.
1 min read

I’ve enabled dark mode for this site using the prefers-color-scheme media query. Below, I present (in it’s entirety) the scss code for dark mode on this site. The media query also works for non-sass stylesheets, you would just need to alter the code to use vanilla css syntax.

As of this writing, it’s supported in Firefox 67+, Safari 12.1+.

@media (prefers-color-scheme: dark) {
  // Override body style
  body {
    // Set primary colors
    background: #111;
    color: #F7F7F7;

    // Image borders
    img {
      border-color: #222;
    }

    // override h1, h2 underlines to be dark.
    > .container h1, > .container h2 {
      border-bottom: 1px solid #222;
    }
  }

  // Override links inside of h* elements to be dark.
  @for $index from 1 through 6 {
    h#{$index} {
      a, a:link {
        color: #F7F7F7;
      }

      a:visited, a:active {
        color: #DDD;
      }
    }
  }
}

Subscribe to my Newsletter

Like this post? Subscribe to get notified for future posts like this.

Change Log

  • 3/26/2019 - Initial Revision

Found a typo or technical problem? file an issue!