Jump to content

Dark Theme using CSS: Difference between revisions

From WikiJournal
Tag: 2017 source edit
mNo edit summary
Line 1: Line 1:
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.
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 ===
== 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.
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.


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


=== Using CSS Variables for Theming ===
== Using CSS Variables for Theming ==
One of the most convenient ways to implement a dark theme is by using CSS variables (<code>custom properties</code>). This makes it easy to manage colors and other style parameters.
One of the most convenient ways to implement a dark theme is by using CSS variables (<code>custom properties</code>). This makes it easy to manage colors and other style parameters.


Line 36: Line 36:
Now, simply add the <code>.dark-theme</code> class to <code><html></code> or <code><body></code> to change the colors.
Now, simply add the <code>.dark-theme</code> class to <code><html></code> or <code><body></code> to change the colors.


=== Switching Themes with JavaScript ===
== Switching Themes with JavaScript ==
To allow users to switch between light and dark themes, you can use JavaScript:
To allow users to switch between light and dark themes, you can use JavaScript:
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
Line 59: Line 59:
This way, the user's choice is preserved after the page reloads.
This way, the user's choice is preserved after the page reloads.


=== Automatic Detection of System Theme ===
== Automatic Detection of System Theme ==
If you want to respect the user's system settings, you can use <code>prefers-color-scheme</code>. This media query automatically applies the appropriate theme:
If you want to respect the user's system settings, you can use <code>prefers-color-scheme</code>. This media query automatically applies the appropriate theme:
<syntaxhighlight lang="css" copy>
<syntaxhighlight lang="css" copy>
Line 71: Line 71:
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.
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 ===
== Combining Automatic Detection and Manual Selection ==
To account for both methods, you can first check if there is a saved theme choice in <code>localStorage</code>. If not, apply the system settings:
To account for both methods, you can first check if there is a saved theme choice in <code>localStorage</code>. If not, apply the system settings:
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
Line 84: Line 84:
</syntaxhighlight>
</syntaxhighlight>


=== Creating a User-Friendly Toggle ===
== Creating a User-Friendly Toggle ==
Now, let's add a theme toggle button in HTML:
Now, let's add a theme toggle button in HTML:
<syntaxhighlight lang="html" copy>
<syntaxhighlight lang="html" copy>
Line 91: Line 91:
The button allows the user to manually change the theme, and the logic for saving the choice makes the interaction convenient.
The button allows the user to manually change the theme, and the logic for saving the choice makes the interaction convenient.


=== Enhancing Transition Animations ===
== Enhancing Transition Animations ==
To make the theme switch look smooth, you can add an animation:
To make the theme switch look smooth, you can add an animation:
<syntaxhighlight lang="css" copy>
<syntaxhighlight lang="css" copy>
Line 189: Line 189:
</syntaxhighlight>
</syntaxhighlight>


=== Conclusion ===
== 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 <code>prefers-color-scheme</code> and <code>localStorage</code> gives users flexibility in their choices. As a result, the website will be adaptive and comfortable to use in any lighting conditions.
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 <code>prefers-color-scheme</code> and <code>localStorage</code> gives users flexibility in their choices. As a result, the website will be adaptive and comfortable to use in any lighting conditions.



Revision as of 16:47, 5 February 2025

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Dark and Light Theme</title>
    <style>
        /* Basic styles and CSS variables */
        :root {
            --bg-color: #ffffff;
            --text-color: #000000;
        }

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

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            transition: background-color 0.3s, color 0.3s;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: var(--text-color);
            color: var(--bg-color);
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s, color 0.3s;
        }

        /* Animation for smooth transitions */
        * {
            transition: background-color 0.3s, color 0.3s;
        }

        /* Automatic detection of system theme */
        @media (prefers-color-scheme: dark) {
            :root {
                --bg-color: #121212;
                --text-color: #ffffff;
            }
        }
    </style>
</head>
<body>
    <h1>Example of Dark and Light Theme</h1>
    <p>This is an example of implementing dark and light themes using CSS, JavaScript, and localStorage.</p>
    <button id="theme-toggle">Toggle Theme</button>

    <script>
        // Theme switching logic
        const toggleThemeBtn = document.getElementById('theme-toggle');

        // Check saved settings when the page loads
        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');
        }

        // Toggle theme on click
        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');
            }
        });
    </script>
</body>
</html>

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