DEV Community

Cover image for Mastering Dark Mode in CSS and Sass
KemotiaDev
KemotiaDev

Posted on

Mastering Dark Mode in CSS and Sass

Dark mode is a popular design trend that has gained a lot of attention in recent years. The idea behind dark mode is to provide a low-light interface that reduces eye strain and improves visibility in low-light environments. In this article, we will explore how to handle dark mode in CSS and Sass.

First, let's define some basic CSS variables that we will use to handle dark mode. We will use CSS variables to store the primary and secondary colors, as well as the text and background colors, for both light and dark mode.

:root {
  --primary-color-light: #ff0000;
  --secondary-color-light: #00ff00;
  --text-color-light: #000000;
  --background-color-light: #ffffff;

  --primary-color-dark: #660000;
  --secondary-color-dark: #006600;
  --text-color-dark: #ffffff;
  --background-color-dark: #000000;
}
Enter fullscreen mode Exit fullscreen mode

Next, we need to create a CSS class that will toggle between light and dark mode. We will use the prefers-color-scheme media query to check the user's preferred color scheme and apply the appropriate CSS variables.

.dark-mode {
  --primary-color: var(--primary-color-dark);
  --secondary-color: var(--secondary-color-dark);
  --text-color: var(--text-color-dark);
  --background-color: var(--background-color-dark);
}

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

Now, we can use these CSS variables in our CSS and Sass files to handle dark mode. For example, we can use the --primary-color variable to set the background color of a button:

.btn {
  background-color: var(--primary-color);
  color: var(--text-color);
}
Enter fullscreen mode Exit fullscreen mode

In Sass, we can use the lighten() and darken() functions to create variations of the primary and secondary colors for different states, such as hover and active.

.btn {
  background-color: var(--primary-color);
  color: var(--text-color);

  &:hover {
    background-color: darken(var(--primary-color), 10%);
  }

  &:active {
    background-color: lighten(var(--primary-color), 10%);
  }
}
Enter fullscreen mode Exit fullscreen mode

In addition, we can also use the @if directive to create different styles for light and dark mode.

@if light-mode {
  .btn {
    background-color: var(--primary-color-light);
    color: var(--text-color-light);
  }
} @else {
  .btn {
    background-color: var(--primary-color-dark);
    color: var(--text-color-dark);
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Handling dark mode in CSS and Sass is a powerful way to create a visually appealing and accessible user interface.

Top comments (0)