Site icon Ampersand Tutorials

Light and Dark Theme using Mixin

Quick answer: A light and dark theme with a SASS mixin lets you define your colours once per theme and switch the interface by changing a single variable. Create one mixin that takes the theme colours and applies them to backgrounds, text, and components, then include it with each palette. It can follow the user system preference.

Light and Dark Theme using Mixin and implement in your web projects.

It is possible to switch between a dark and light theme using simple SCSS  / SASS without many code lines. We can leverage Mixin to achieve the change in light and dark themes. Following is the code for creating Mixin which can easily switch between light and dark themes. 

We will leverage two functions lighten and darken inside Mixin two achieve the functionality. Lighten function will help lighten the applied colour, and darken function will help darken the used colour. 

$primary-color: #000000;
$text-color: #3af80a;
$secondary-color: #432396;

@mixin theme($light-theme: true) {
    @if $light-theme{
        background: lighten($primary-color, 100%);
        color: darken ($text-color, 100%);
    }
}

Now create a class called light and apply it to the body tag. Inside the light class now include the theme mixin to enable the theme switch property.

.light{
    @include theme ($light-theme: true);
}

If the $light-theme is true, the HTML page will apply a light theme, the background colour will be light, and the text colour will be dark. If the $light-theme is false, the HTML page will apply a dark theme. 

.light{
    @include theme ($light-theme: false);
}

The above code will create a dark background and light text colour. In the next tutorial, we will learn Extension and Operators in SASS / SCSS.

Official documentation

For the full reference behind this guide, read the official Sass documentation on the mixin at-rule. It is the source the details above are drawn from, and the first place to check when an option or attribute name changes.

Frequently asked questions

How do I switch between light and dark themes in SASS?

Store the colour values in a variable, then include your theme mixin with that palette. Changing the variable swaps the entire theme.

Can SASS follow the user’s system theme automatically?

Yes, use the media prefers color scheme query and set the theme variable based on the prefers dark or light condition.

Should dark mode use a mixin?

A mixin works well because it applies one set of colour rules to every component, keeping the two themes consistent.

Exit mobile version