Styling with CSS

Next, we'll define our styles for both dark and light modes. We'll use CSS variables to make switching themes easier.

/* styles.css */:root {    --bg-color: #ffffff;    --text-color: #000000;    --button-bg-color: #000000;    --button-text-color: #ffffff;}body {    background-color: var(--bg-color);    color: var(--text-color);    font-family: Arial, sans-serif;    transition: background-color 0.3s ease, color 0.3s ease;}.container {    text-align: center;    margin-top: 50px;}button {    background-color: var(--button-bg-color);    color: var(--button-text-color);    border: none;    padding: 10px 20px;    cursor: pointer;    transition: background-color 0.3s ease, color 0.3s ease;}button:hover {    opacity: 0.8;}body.dark-mode {    --bg-color: #333333;    --text-color: #ffffff;    --button-bg-color: #ffffff;    --button-text-color: #000000;}

Adding JavaScript Functionality

Now, we'll add the JavaScript to handle the theme switch. We'll also save the user's preference in localStorage so that their choice persists across sessions.

// script.jsdocument.addEventListener(\\'DOMContentLoaded\\', () => {    const switcher = document.getElementById(\\'modeSwitcher\\');    const currentMode = localStorage.getItem(\\'theme\\') || \\'light\\';    if (currentMode === \\'dark\\') {        document.body.classList.add(\\'dark-mode\\');        switcher.textContent = \\'Switch to Light Mode\\';    }    switcher.addEventListener(\\'click\\', () => {        document.body.classList.toggle(\\'dark-mode\\');        const mode = document.body.classList.contains(\\'dark-mode\\') ? \\'dark\\' : \\'light\\';        switcher.textContent = mode === \\'dark\\' ? \\'Switch to Light Mode\\' : \\'Switch to Dark Mode\\';        localStorage.setItem(\\'theme\\', mode);    });});

Explanation

1. CSS Variables: We use CSS variables to define the colors for both modes, making it easy to switch between them.

2. JavaScript: We add an event listener to the button to toggle the dark-mode class on the body element. We also update the button text based on the current mode and save the mode in localStorage.

3. Persistent Theme: When the page loads, we check localStorage for the user's preference and apply the appropriate theme.

Conclusion

Implementing a dark/light mode switcher enhances user experience by providing visual options that cater to different preferences and conditions. With just a few lines of HTML, CSS, and JavaScript, you can add this valuable feature to your web projects.

Feel free to experiment with more advanced features, such as smooth transitions or additional themes. The possibilities are endless, and your users will appreciate the added flexibility.

Happy coding!

","image":"http://www.luping.net/uploads/20240730/172233036366a8acfbc7557.jpg","datePublished":"2024-07-30T17:06:02+08:00","dateModified":"2024-07-30T17:06:02+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Creating a CSS Dark/Light Mode Switcher

Creating a CSS Dark/Light Mode Switcher

Published on 2024-07-30
Browse:137

Creating a CSS Dark/Light Mode Switcher

Dark and light mode switchers have become increasingly popular, offering users the flexibility to choose their preferred visual experience. Whether it's to reduce eye strain, save battery life, or simply follow personal preference, implementing a dark/light mode switcher can significantly enhance user experience. In this article, we'll guide you through creating a simple yet effective dark/light mode switcher using HTML, CSS, and JavaScript.

Why Implement Dark/Light Mode?

1. User Preference: Some users prefer dark mode for aesthetics or reduced eye strain, especially in low-light environments.

2. Accessibility: Improving accessibility by offering a theme that can help visually impaired users.

3. Battery Saving: On OLED screens, dark mode can save battery life.

Setting Up the HTML Structure

Start by creating a simple HTML structure. We'll need a button to toggle between dark and light modes.



    Dark/Light Mode Switcher

Dark/Light Mode Switcher

Toggle the button to switch between dark and light modes.

Styling with CSS

Next, we'll define our styles for both dark and light modes. We'll use CSS variables to make switching themes easier.

/* styles.css */
:root {
    --bg-color: #ffffff;
    --text-color: #000000;
    --button-bg-color: #000000;
    --button-text-color: #ffffff;
}

body {
    background-color: var(--bg-color);
    color: var(--text-color);
    font-family: Arial, sans-serif;
    transition: background-color 0.3s ease, color 0.3s ease;
}

.container {
    text-align: center;
    margin-top: 50px;
}

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

button:hover {
    opacity: 0.8;
}

body.dark-mode {
    --bg-color: #333333;
    --text-color: #ffffff;
    --button-bg-color: #ffffff;
    --button-text-color: #000000;
}

Adding JavaScript Functionality

Now, we'll add the JavaScript to handle the theme switch. We'll also save the user's preference in localStorage so that their choice persists across sessions.

// script.js
document.addEventListener('DOMContentLoaded', () => {
    const switcher = document.getElementById('modeSwitcher');
    const currentMode = localStorage.getItem('theme') || 'light';

    if (currentMode === 'dark') {
        document.body.classList.add('dark-mode');
        switcher.textContent = 'Switch to Light Mode';
    }

    switcher.addEventListener('click', () => {
        document.body.classList.toggle('dark-mode');
        const mode = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
        switcher.textContent = mode === 'dark' ? 'Switch to Light Mode' : 'Switch to Dark Mode';
        localStorage.setItem('theme', mode);
    });
});

Explanation

1. CSS Variables: We use CSS variables to define the colors for both modes, making it easy to switch between them.

2. JavaScript: We add an event listener to the button to toggle the dark-mode class on the body element. We also update the button text based on the current mode and save the mode in localStorage.

3. Persistent Theme: When the page loads, we check localStorage for the user's preference and apply the appropriate theme.

Conclusion

Implementing a dark/light mode switcher enhances user experience by providing visual options that cater to different preferences and conditions. With just a few lines of HTML, CSS, and JavaScript, you can add this valuable feature to your web projects.

Feel free to experiment with more advanced features, such as smooth transitions or additional themes. The possibilities are endless, and your users will appreciate the added flexibility.

Happy coding!

Release Statement This article is reproduced at: https://dev.to/mdhassanpatwary/creating-a-css-darklight-mode-switcher-26cd?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3