2. Add necessary elements to the body. Inside the body tag, we\\'ll add the following elements:

    

Light/Dark Mode Toggle

Click the toggle below to switch between dark and light modes.

This is what our plain index.html file looks like:

\\\"How

Adding CSS Styling for Light and Dark Modes

In this section, we’ll style our HTML elements and create light and dark modes. We’ll also use transitions for smooth color changes and control the visibility of sun and moon icons based on the current mode.

3. Define CSS variables for light and dark colors. Open the style.css file in your text editor. We’ll define CSS variables for dark and light colors using the :root selector. This allows for easy theme customization later on. If you want to change the dark or light colors, you only need to update them in one place.

/* Root selector for defining global CSS variables */:root {  --clr-dark: #333;  /* Dark color for text in light mode, background in dark mode */  --clr-light: #fff; /* Light color for background in light mode, text in dark mode */}

4. Set up basic CSS styles. Add styles for the body, .container, and h1 elements to establish the layout and typography of your page. You can customize these elements the way you like.

/* Base styles for the body */body {    font-family: Arial, sans-serif;    display: flex;    justify-content: center;    align-items: center;    height: 100vh;    margin: 0;    background-color: var(--clr-light);    color: var(--clr-dark);    transition: background-color 0.3s, color 0.3s;}/* Container for centering content */.container {    text-align: center;}/* Heading styles */h1 {    margin-bottom: 20px;}

5. Add CSS styling for dark mode. Create a CSS class named .dark-mode that swaps the background and text colors when applied to an element.

/* Styles for dark mode */.dark-mode {    background-color: var(--clr-dark);    color: var(--clr-light);}

6. Style the toggle icons. Add styles to the sun and moon SVG icons and control their visibility based on the current mode.

/* Styles for the toggle container */.toggle-container {    cursor: pointer;}/* Styles for the sun and moon icons */.sun-icon, .moon-icon {    width: 24px;    height: 24px;    transition: opacity 0.3s;}/* Hide moon icon by default (light mode) */.moon-icon {    display: none;}/* Show moon icon and hide sun icon in dark mode */.dark-mode .sun-icon {    display: none;}.dark-mode .moon-icon {    display: inline-block;}

With these CSS styles, your page will have a default light theme. The cursor: pointer property makes it clear that the toggle is clickable.

\\\"How

Implementing JavaScript Functionality

Now that we have our HTML structure and CSS styling in place, it\\'s time to add interactivity to our dark mode toggle with JavaScript and implement local storage to remember the user\\'s preference.

7. Select DOM elements. Open the script.js file and select the DOM elements we want to modify, the themeToggle ID, which contains our toggle button.

const themeToggle = document.getElementById(\\'themeToggle\\');const body = document.body;

8. Add event listeners to the toggle button. This is the core functionality of the dark mode toggle. Add an event listener to the themeToggle element to detect when the user clicks on it. It will add the dark-mode class to the body element if it’s absent, or removes the class if present.

themeToggle.addEventListener(\\'click\\', () => {    body.classList.toggle(\\'dark-mode\\');});

At this point, the toggle switch is functional, and clicking on it will switch between light and dark modes. However, if you reload the page while in dark mode, the website will revert to its default light mode.

9. Save user theme preferences in local storage. To save the user\\'s theme preference even after the browser is closed, we\\'ll use the localStorage object. Inside the event listener callback function, it checks if the body element has the dark-mode class.

themeToggle.addEventListener(\\'click\\', () => {    body.classList.toggle(\\'dark-mode\\');    // Store user preference in local storage    if (body.classList.contains(\\'dark-mode\\')) {        localStorage.setItem(\\'theme\\', \\'dark-mode\\');    } else {        localStorage.setItem(\\'theme\\', \\'\\');    }});

10. Check for a saved theme preference. When the page loads, we want to check if there\\'s a saved theme preference in the local storage. Use localStorage.getItem() to retrieve the value associated with the \\'theme\\' key. If a \\'dark-mode\\' preference exists in the local storage, apply the dark mode theme immediately by adding the dark-mode class to the body element.

Note: Make sure to place the getItem() method before the event listener to ensure it runs on page load.

// Check if user preference exists in local storageconst currentTheme = localStorage.getItem(\\'theme\\');if (currentTheme) {    body.classList.add(currentTheme);}

The Dark Mode Toggle in Action

We\\'ve implemented all the necessary components for our dark mode toggle, so let\\'s see it in action. Try clicking the toggle switch to see the smooth transition between light and dark themes. Refresh the page to verify your theme preference is remembered.

Check out the complete source code on this GitHub repository.

Tips for Dark Mode Implementation

Creating a dark mode toggle is just the beginning. To create a user-friendly dark mode experience, there are several best practices to keep in mind.

Tip #1: Choose the Right Colors for Dark Mode

Selecting colors for dark mode involves more than simply inverting your light theme. The goal is to create a contrast between text and background colors for readability. Use tools like color contrast checkers to verify that your chosen colors meet WCAG (Web Content Accessibility Guidelines) standards. Remember, a well-designed dark mode should be easy on the eyes and work well across devices.

Tip #2: Create a User-Friendly Toggle Button

Create a clear visual distinction between light and dark modes to help users identify each mode easily. Your toggle switch or button should clearly show the current mode. You can implement effective approaches such as a sun and moon icon toggle, which is used in this article and is an easily recognizable choice, a light and dark mode text button, or a sliding switch with light/dark mode labels. Whichever design you choose, make sure it\\'s consistent with your user interface and provides clear feedback when the user interacts with it.

Tip #3: Implement Smooth Transitions

To create a more polished user experience, use CSS transitions or animations for a seamless shift between light and dark modes. Make sure that all elements, including images and icons, smoothly transition to the new color scheme. This can be done by adjusting opacity, brightness, or swapping out images for dark mode-specific versions.

Conclusion

Adding a dark mode toggle to your website greatly improves user experience. This is not just about aesthetics but also usability and accessibility. It allows users to view content comfortably based on their preferences and lighting conditions.

Throughout this article, we\\'ve walked through the process of creating a simple dark mode toggle, covering HTML structure, CSS styling for light and dark themes, JavaScript functionality, and storing user preference. The key is to keep it simple and user-friendly. Don\\'t forget to test your dark mode thoroughly to ensure all elements remain readable and functional.

Now it\\'s your turn to create your own dark mode toggle! Share your CodePen or GitHub link in the comments below.

Further Reading

Check out these resources to learn more about dark mode implementation and advanced techniques:

","image":"http://www.luping.net/uploads/20240915/172635913166e6265b39ddf.png","datePublished":"2024-11-04T23:31:12+08:00","dateModified":"2024-11-04T23:31:12+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 HTML、CSS 和 JavaScript 建立深色模式切換

如何使用 HTML、CSS 和 JavaScript 建立深色模式切換

發佈於2024-11-04
瀏覽:203

Light or Dark? One-Click Theme Switching for Website Accessibility

Websites and applications now typically have two distinct themes: a light theme for better visibility during the day and a dark theme for less eye strain at night. To provide the best experience, your website should allow users to easily toggle between these themes based on their preferences. This article will guide you on creating a dark mode toggle for your website using HTML, CSS, and JavaScript, enabling users to switch between light and dark themes with a single click.

In this tutorial, we'll build a sun and moon toggle button to represent light and dark modes. When a user clicks the button, the website will smoothly transition between these two modes. We'll also save the user's theme preference in local storage for future visits.

See the demo or the complete source code on this GitHub repository. You can learn interactively with this step-by-step guide, or scroll down for a detailed tutorial.

Prerequisites

Before we begin, make sure you have:

  • Basic knowledge of HTML, CSS, and JavaScript
  • A text editor or IDE (e.g., Visual Studio Code, Sublime Text)
  • A web browser for testing

Setting Up the HTML Structure

First, we'll create the basic HTML structure and add the necessary elements to build our toggle button and page content.

1. Create a new HTML file. Open your text editor and create a new index.html file with the basic HTML structure, including DOCTYPE, HTML, head, and body tags. Add the title tag for the page and import the external style.css and script.js files.



    
    
    Light/Dark Mode Toggle
    


    


2. Add necessary elements to the body. Inside the body tag, we'll add the following elements:

  • A container div to wrap all our content
  • An h1 title for the page
  • A p paragraph for a brief description
  • A toggle-container div that will include our toggle switch
  • Sun and moon SVG icons
    

Light/Dark Mode Toggle

Click the toggle below to switch between dark and light modes.

This is what our plain index.html file looks like:

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

Adding CSS Styling for Light and Dark Modes

In this section, we’ll style our HTML elements and create light and dark modes. We’ll also use transitions for smooth color changes and control the visibility of sun and moon icons based on the current mode.

3. Define CSS variables for light and dark colors. Open the style.css file in your text editor. We’ll define CSS variables for dark and light colors using the :root selector. This allows for easy theme customization later on. If you want to change the dark or light colors, you only need to update them in one place.

/* Root selector for defining global CSS variables */
:root {
  --clr-dark: #333;  /* Dark color for text in light mode, background in dark mode */
  --clr-light: #fff; /* Light color for background in light mode, text in dark mode */
}

4. Set up basic CSS styles. Add styles for the body, .container, and h1 elements to establish the layout and typography of your page. You can customize these elements the way you like.

  • body Center the content both vertically and horizontally using CSS variables for colors and a transition for smooth color changes.
  • .container Center the content within our container.
  • h1 Add some space below the heading.
/* Base styles for the body */
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: var(--clr-light);
    color: var(--clr-dark);
    transition: background-color 0.3s, color 0.3s;
}
/* Container for centering content */
.container {
    text-align: center;
}
/* Heading styles */
h1 {
    margin-bottom: 20px;
}

5. Add CSS styling for dark mode. Create a CSS class named .dark-mode that swaps the background and text colors when applied to an element.

/* Styles for dark mode */
.dark-mode {
    background-color: var(--clr-dark);
    color: var(--clr-light);
}

6. Style the toggle icons. Add styles to the sun and moon SVG icons and control their visibility based on the current mode.

/* Styles for the toggle container */
.toggle-container {
    cursor: pointer;
}
/* Styles for the sun and moon icons */
.sun-icon, .moon-icon {
    width: 24px;
    height: 24px;
    transition: opacity 0.3s;
}
/* Hide moon icon by default (light mode) */
.moon-icon {
    display: none;
}
/* Show moon icon and hide sun icon in dark mode */
.dark-mode .sun-icon {
    display: none;
}
.dark-mode .moon-icon {
    display: inline-block;
}

With these CSS styles, your page will have a default light theme. The cursor: pointer property makes it clear that the toggle is clickable.

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

Implementing JavaScript Functionality

Now that we have our HTML structure and CSS styling in place, it's time to add interactivity to our dark mode toggle with JavaScript and implement local storage to remember the user's preference.

7. Select DOM elements. Open the script.js file and select the DOM elements we want to modify, the themeToggle ID, which contains our toggle button.

const themeToggle = document.getElementById('themeToggle');
const body = document.body;

8. Add event listeners to the toggle button. This is the core functionality of the dark mode toggle. Add an event listener to the themeToggle element to detect when the user clicks on it. It will add the dark-mode class to the body element if it’s absent, or removes the class if present.

themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');
});

At this point, the toggle switch is functional, and clicking on it will switch between light and dark modes. However, if you reload the page while in dark mode, the website will revert to its default light mode.

9. Save user theme preferences in local storage. To save the user's theme preference even after the browser is closed, we'll use the localStorage object. Inside the event listener callback function, it checks if the body element has the dark-mode class.

  • If it does, localStorage.setItem() saves the 'dark-mode' value to the 'theme' key.
  • If it doesn't, localStorage.setItem() saves an empty string to the 'theme' key.
themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');

    // Store user preference in local storage
    if (body.classList.contains('dark-mode')) {
        localStorage.setItem('theme', 'dark-mode');
    } else {
        localStorage.setItem('theme', '');
    }
});

10. Check for a saved theme preference. When the page loads, we want to check if there's a saved theme preference in the local storage. Use localStorage.getItem() to retrieve the value associated with the 'theme' key. If a 'dark-mode' preference exists in the local storage, apply the dark mode theme immediately by adding the dark-mode class to the body element.

Note: Make sure to place the getItem() method before the event listener to ensure it runs on page load.

// Check if user preference exists in local storage
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
    body.classList.add(currentTheme);
}

The Dark Mode Toggle in Action

We've implemented all the necessary components for our dark mode toggle, so let's see it in action. Try clicking the toggle switch to see the smooth transition between light and dark themes. Refresh the page to verify your theme preference is remembered.

Check out the complete source code on this GitHub repository.

Tips for Dark Mode Implementation

Creating a dark mode toggle is just the beginning. To create a user-friendly dark mode experience, there are several best practices to keep in mind.

Tip #1: Choose the Right Colors for Dark Mode

Selecting colors for dark mode involves more than simply inverting your light theme. The goal is to create a contrast between text and background colors for readability. Use tools like color contrast checkers to verify that your chosen colors meet WCAG (Web Content Accessibility Guidelines) standards. Remember, a well-designed dark mode should be easy on the eyes and work well across devices.

Tip #2: Create a User-Friendly Toggle Button

Create a clear visual distinction between light and dark modes to help users identify each mode easily. Your toggle switch or button should clearly show the current mode. You can implement effective approaches such as a sun and moon icon toggle, which is used in this article and is an easily recognizable choice, a light and dark mode text button, or a sliding switch with light/dark mode labels. Whichever design you choose, make sure it's consistent with your user interface and provides clear feedback when the user interacts with it.

Tip #3: Implement Smooth Transitions

To create a more polished user experience, use CSS transitions or animations for a seamless shift between light and dark modes. Make sure that all elements, including images and icons, smoothly transition to the new color scheme. This can be done by adjusting opacity, brightness, or swapping out images for dark mode-specific versions.

Conclusion

Adding a dark mode toggle to your website greatly improves user experience. This is not just about aesthetics but also usability and accessibility. It allows users to view content comfortably based on their preferences and lighting conditions.

Throughout this article, we've walked through the process of creating a simple dark mode toggle, covering HTML structure, CSS styling for light and dark themes, JavaScript functionality, and storing user preference. The key is to keep it simple and user-friendly. Don't forget to test your dark mode thoroughly to ensure all elements remain readable and functional.

Now it's your turn to create your own dark mode toggle! Share your CodePen or GitHub link in the comments below.

Further Reading

Check out these resources to learn more about dark mode implementation and advanced techniques:

  • Dark theme - Material Design: Learn about dark mode implementation, anatomy, properties, and best practices from Material Design guidelines.
  • Top 20 CSS Toggle Switches [2024] - LambdaTest: Explore various CSS toggle switch designs for your website.
版本聲明 本文轉載於:https://dev.to/warish/how-to-create-a-dark-mode-toggle-with-html-css-and-javascript-378m?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-26
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內...
    程式設計 發佈於2024-12-26
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSocke...
    程式設計 發佈於2024-12-26
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-26
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-12-26
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-26
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-26
  • 如何在 PHP 中轉換所有類型的智慧引號?
    如何在 PHP 中轉換所有類型的智慧引號?
    在 PHP 中轉換所有類型的智慧引號智慧引號是用來取代常規直引號(' 和")的印刷標記。它們提供了更精緻和然而,軟體應用程式通常會在不同類型的智能引號之間進行轉換,從而導致不一致。智能引號中的挑戰轉換轉換智慧引號的困難在於用於表示它們的各種編碼和字符,不同的作業系統和軟體程式採用自...
    程式設計 發佈於2024-12-26
  • 循環 JavaScript 陣列有哪些不同的方法?
    循環 JavaScript 陣列有哪些不同的方法?
    使用 JavaScript 迴圈遍歷陣列遍歷陣列的元素是 JavaScript 中常見的任務。有多種方法可供選擇,每種方法都有自己的優點和限制。讓我們探討一下這些選項:陣列1。 for-of 遵循(ES2015 )此循環使用迭代器迭代數組的值:const arr = ["a", ...
    程式設計 發佈於2024-12-26
  • 如何在 Python 中有效地暫停 Selenium WebDriver 執行?
    如何在 Python 中有效地暫停 Selenium WebDriver 執行?
    Selenium WebDriver 中的等待與條件語句問題: 如何在 Python 中暫停 Selenium WebDriver 執行幾毫秒? 答案:雖然time.sleep() 函數可用於暫停執行指定的秒數,在 Selenium WebDriver 自動化中一般不建議使用。 使用 Seleniu...
    程式設計 發佈於2024-12-26
  • C++ 賦值運算子應該是虛擬的嗎?
    C++ 賦值運算子應該是虛擬的嗎?
    C 中的虛擬賦值運算子及其必要性雖然賦值運算子可以在C 中定義為虛擬,但這不是強制要求。然而,這種虛擬聲明引發了關於虛擬性的必要性以及其他運算子是否也可以虛擬的問題。 虛擬賦值運算子的案例賦值運算子本質上並非虛擬。然而,當將繼承類別的物件分配給基類變數時,它就變得必要了。這種動態綁定保證了呼叫基於物...
    程式設計 發佈於2024-12-26
  • JavaScript 中的 Let 與 Var:範圍和用法有什麼區別?
    JavaScript 中的 Let 與 Var:範圍和用法有什麼區別?
    JavaScript 中的Let 與Var:揭秘範圍和臨時死區在ECMAScript 6 中引入,let 語句引發了開發人員的語句引發了開發人員的語句引發了開發人員的語句困惑,特別是它與已建立的var 關鍵字有何不同。本文深入研究了這兩個變數聲明之間的細微差別,重點介紹了它們的作用域規則和最佳用例。...
    程式設計 發佈於2024-12-26
  • 如何使用 JavaScript 用逗號分割字串,忽略雙引號內的逗號?
    如何使用 JavaScript 用逗號分割字串,忽略雙引號內的逗號?
    使用JavaScript 用逗號分割字串,忽略雙引號內的逗號解決用逗號分割字串同時保留double 的挑戰-引用段,我們可以在JavaScript 中使用正規表示式。方法如下:var str = 'a, b, c, "d, e, f", g, h'; var arr = str....
    程式設計 發佈於2024-12-26
  • JavaScript 函數表達式中的感嘆號 (!) 有何作用?
    JavaScript 函數表達式中的感嘆號 (!) 有何作用?
    揭示函數表達式中感嘆號的用途在JavaScript 中,執行程式碼時,前面遇到感嘆號(!)函數可能會引發一些問題。讓我們深入研究一下它的功能及其在語法中的作用。 JavaScript 的語法規定,以「function foo() {}」形式宣告的函數是函數聲明,需要呼叫才能執行。然而,預處理帶有感嘆...
    程式設計 發佈於2024-12-26
  • 如何在 Go 中以程式設計方式存取文件組 ID (GID)?
    如何在 Go 中以程式設計方式存取文件組 ID (GID)?
    在Go 中訪問文件組ID (GID)在Go 中,os.Stat() 函數檢索文件信息,包括其系統資訊-特定屬性。此資訊儲存在 syscall.Sys 介面中。雖然列印介面直接顯示 GID,但以程式設計方式存取它會帶來挑戰。 要以 Linux 系統的字串形式取得 GID:file_info, _ :=...
    程式設計 發佈於2024-12-26

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3