Jump to content

Dark Theme using CSS

From WikiJournal
Revision as of 13:03, 10 February 2025 by Philip (talk | contribs) (Example of Light and Dark Theme Switching)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In recent years, dark mode has become an integral part of modern web design. It not only reduces eye strain when working in low-light conditions but also saves battery life on devices with OLED displays. Implementing a dark theme on a website using CSS is quite simple, but it is important to do it correctly so that users can easily switch between light and dark versions.

Basic Principles of Working with Themes

Dark and light themes are two sets of styles that can be dynamically applied to website elements. Ideally, users should be given the option to choose which theme to use, but system preferences of the operating system can also be taken into account.

There are two main ways to implement a dark theme:

  • Using CSS variables and switching styles via JavaScript.
  • Automatically applying the theme based on system settings using prefers-color-scheme.

Both approaches can be combined to make theme handling more flexible.

Using CSS Variables for Theming

One of the most convenient ways to implement a dark theme is by using CSS variables (custom properties). This makes it easy to manage colors and other style parameters.

First, let's create root variables in :root that will be used throughout the document:

:root {
     --bg-color: #ffffff;
     --text-color: #000000;
 }
 
 .dark-theme {
     --bg-color: #121212;
     --text-color: #ffffff;
 }

Then, apply these variables to the page elements:

body {
     background-color: var(--bg-color);
     color: var(--text-color);
     transition: background-color 0.3s, color 0.3s;
 }

Now, simply add the .dark-theme class to <html> or <body> to change the colors.

Switching Themes with JavaScript

To allow users to switch between light and dark themes, you can use JavaScript:

const toggleThemeBtn = document.getElementById('theme-toggle');
 
 toggleThemeBtn.addEventListener('click', () => {
     document.documentElement.classList.toggle('dark-theme');
 
     // Save the user's choice in localStorage
     if (document.documentElement.classList.contains('dark-theme')) {
         localStorage.setItem('theme', 'dark');
     } else {
         localStorage.setItem('theme', 'light');
     }
 });
 
 // Check saved settings when the page loads
 if (localStorage.getItem('theme') === 'dark') {
     document.documentElement.classList.add('dark-theme');
 }

This way, the user's choice is preserved after the page reloads.

Automatic Detection of System Theme

If you want to respect the user's system settings, you can use prefers-color-scheme. This media query automatically applies the appropriate theme:

@media (prefers-color-scheme: dark) {
     :root {
         --bg-color: #121212;
         --text-color: #ffffff;
     }
 }

This method is convenient because it immediately adapts the website to the system preferences. However, if the user wants to manually select a theme, you will need to combine this approach with JavaScript.

Combining Automatic Detection and Manual Selection

To account for both methods, you can first check if there is a saved theme choice in localStorage. If not, apply the system settings:

const userTheme = localStorage.getItem('theme');
 const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
 
 if (userTheme) {
     document.documentElement.classList.toggle('dark-theme', userTheme === 'dark');
 } else {
     document.documentElement.classList.toggle('dark-theme', systemTheme === 'dark');
 }

Creating a User-Friendly Toggle

Now, let's add a theme toggle button in HTML:

<button id="theme-toggle">Toggle Theme</button>

The button allows the user to manually change the theme, and the logic for saving the choice makes the interaction convenient.

Enhancing Transition Animations

To make the theme switch look smooth, you can add an animation:

* {
     transition: background-color 0.3s, color 0.3s;
 }

This creates a soft dimming or brightening effect when switching themes.

Example of Light and Dark Theme Switching

Test code at separate page

Conclusion

Implementing a dark theme on a website using CSS and JavaScript is a relatively simple but important task. Using CSS variables makes the code convenient and scalable, while combining prefers-color-scheme and localStorage gives users flexibility in their choices. As a result, the website will be adaptive and comfortable to use in any lighting conditions.

Related CSS Articles