Skip to main content
Practice

Changing Themes Using CSS and JavaScript

Let's learn how to change themes using JavaScript.


Setting Theme Colors Using CSS Variables

CSS variables (or "custom properties") are used to store reusable values in a webpage.

In this example, we'll store different color values for each theme as variables so that we can easily reference and change them.

CSS
[data-theme='light'] {
--bg-color: #fff;
--text-color: #000;
...;
}

Styling Based on data-theme

You can use the data-theme attribute in CSS to apply styles for a specific theme.

By doing so, changing the data-theme attribute in the HTML document will automatically apply the corresponding theme's styles.

CSS
[data-theme='dark'] {
--bg-color: #111;
--text-color: #c3b6a2;
...;
}

Defining Color Values for Each Theme

Define the color values for each theme as CSS variables, so when a theme is selected, these color values get applied across the whole page.


Setting the Theme and Changing the data-theme Attribute

Use JavaScript to dynamically change the data-theme attribute and save the user's theme preference in the browser's local storage. This ensures that the user's selected theme persists when they revisit the website.


Changing the data-theme Attribute Based on the Selected Theme

Change the value of the data-theme attribute based on the user's selected theme. This can be done using JavaScript’s setAttribute method.

const setTheme = (theme) => {
document.documentElement.setAttribute('data-theme', theme);
};

Storing User's Theme Preference Using Local Storage

Local storage is used to store information in the web browser.

By storing the user's theme preference in local storage, the selected theme is maintained even if the page is refreshed or revisited later.

localStorage.setItem('theme', t1);

Initial Theme Setting Logic

When the page first loads, check the user's theme setting from local storage and apply it.

If no theme setting is found in local storage, the default 'light' theme is set.

const theme = localStorage.getItem('theme') || 'light';
setTheme(theme);

By combining CSS and JavaScript in this way, we provide a user-friendly theme switching feature that remembers the user's choice for a consistent experience upon their return.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.