본문으로 건너뛰기

Controlling Light/Dark Themes

Changing Themes with 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 on a web page.

In this example, various color values depending on the theme are stored as variables, making it easy to reference and change them.

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

Styling Based on data-theme

In CSS, use the value of the data-theme attribute to apply styles according to the respective theme.

By doing this, simply changing the data-theme attribute in the HTML document automatically applies the styles for that particular theme.

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

Defining Color Values for Each Theme

Define different color values as CSS variables for each theme, so that these colors are applied throughout the page when that theme is selected.


Setting the Theme and Changing the data-theme Attribute

Use JavaScript to dynamically change the data-theme attribute and store the user's theme choice in the browser's internal storage, Local Storage, to maintain the selected theme when the user revisits the website.


Setting the Theme and Changing the data-theme Attribute

Change the value of the data-theme attribute according to the selected theme. This change is performed using the setAttribute method in JavaScript.

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

Saving User's Theme Settings Using Local Storage

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

By saving the user's theme choice in Local Storage, the same theme can be maintained even when the page is refreshed or visited again later.

localStorage.setItem('theme', t1);

Initial Theme Setting Logic

When the page first loads, it looks for the user's theme setting in Local Storage and applies that setting.

If there is no theme setting stored in Local Storage, the default is set to the 'light' theme.

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

By combining CSS and JavaScript in this way, a user-friendly theme changing feature is provided, remembering the user's choice to offer the same experience even on return visits.