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
瀏覽:485

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刪除
最新教學 更多>
  • Polyfills-填充物還是縫隙? (第 1 部分)
    Polyfills-填充物還是縫隙? (第 1 部分)
    幾天前,我們在組織的 Teams 聊天中收到一條優先訊息,內容如下:發現安全漏洞 - 偵測到 Polyfill JavaScript - HIGH。 舉個例子,我在一家大型銀行公司工作,你必須知道,銀行和安全漏洞就像主要的敵人。因此,我們開始深入研究這個問題,並在幾個小時內解決了這個問題,我將在下...
    程式設計 發佈於2024-11-05
  • 移位運算子與位元簡寫賦值
    移位運算子與位元簡寫賦值
    1。移位運算子 :向右移動。 >>>:無符號右移(零填充)。 2.移位運算子的一般語法 value > num-bits:將值位向右移動,保留符號位。 value >>> num-bits:透過在左側插入零將值位向右移動。 3.左移 每次左移都會導致該值的所有位元向左移動一位。 右側插入0...
    程式設計 發佈於2024-11-05
  • 如何使用 VBA 從 Excel 建立與 MySQL 資料庫的連線?
    如何使用 VBA 從 Excel 建立與 MySQL 資料庫的連線?
    VBA如何在Excel中連接到MySQL資料庫? 使用VBA連接到MySQL資料庫嘗試連接使用 VBA 在 Excel 中存取 MySQL 資料庫有時可能具有挑戰性。在您的情況下,您在嘗試建立連線時遇到錯誤。 若要使用 VBA 成功連線至 MySQL 資料庫,請依照下列步驟操作:Sub Connec...
    程式設計 發佈於2024-11-05
  • 測試自動化:使用 Java 和 TestNG 進行 Selenium 指南
    測試自動化:使用 Java 和 TestNG 進行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    程式設計 發佈於2024-11-05
  • 我對 DuckDuckGo 登陸頁面的看法
    我對 DuckDuckGo 登陸頁面的看法
    「為什麼不穀歌一下呢?」是我在對話中得到的常見答案。谷歌的無所不在甚至催生了新的動詞「Google」。但是我寫的程式碼越多,我就越質疑我每天使用的數位工具。也許我對谷歌使用我的個人資訊的方式不再感到滿意。或者我們很多人依賴谷歌進行互聯網搜索和其他應用程序,說實話,我厭倦了在搜索某個主題或產品後彈出的...
    程式設計 發佈於2024-11-05
  • 為什麼 Turbo C++ 的「cin」只讀取第一個字?
    為什麼 Turbo C++ 的「cin」只讀取第一個字?
    Turbo C 的「cin」限制:僅讀取第一個單字在Turbo C 中,「cin」輸入運算符有一個處理字元數組時的限制。具體來說,它只會讀取直到遇到空白字元(例如空格或換行符)。嘗試讀取多字輸入時,這可能會導致意外行為。 請考慮以下 Turbo C 代碼:#include <iostream....
    程式設計 發佈於2024-11-05
  • 使用 Buildpack 建立 Spring Boot 應用程式的 Docker 映像
    使用 Buildpack 建立 Spring Boot 應用程式的 Docker 映像
    介绍 您已经创建了一个 Spring Boot 应用程序。它在您的本地计算机上运行良好,现在您需要将该应用程序部署到其他地方。在某些平台上,您可以直接提交jar文件,它将被部署。在某些地方,您可以启动虚拟机,下载源代码,构建并运行它。但是,大多数时候您需要使用容器来部署应用程序。大...
    程式設計 發佈於2024-11-05
  • 如何保護 PHP 程式碼免於未經授權的存取?
    如何保護 PHP 程式碼免於未經授權的存取?
    保護PHP 代碼免於未經授權的訪問保護PHP 軟體背後的智慧財產權對於防止其濫用或盜竊至關重要。為了解決這個問題,可以使用多種方法來混淆和防止未經授權的存取您的程式碼。 一個有效的方法是利用 PHP 加速器。這些工具透過快取頻繁執行的部分來增強程式碼的效能。第二個好處是,它們使反編譯和逆向工程程式碼...
    程式設計 發佈於2024-11-05
  • React:了解 React 的事件系統
    React:了解 React 的事件系統
    Overview of React's Event System What is a Synthetic Event? Synthetic events are an event-handling mechanism designed by React to ach...
    程式設計 發佈於2024-11-05
  • 為什麼在使用 Multipart/Form-Data POST 請求時會收到 301 Moved Permanently 錯誤?
    為什麼在使用 Multipart/Form-Data POST 請求時會收到 301 Moved Permanently 錯誤?
    Multipart/Form-Data POSTsMultipart/Form-Data POSTs嘗試使用multipart/form-data POST 資料時,可能會出現類似所提供的錯誤訊息遭遇。理解問題需要檢視問題的構成。遇到的錯誤是 301 Moved Permanently 回應,表示資...
    程式設計 發佈於2024-11-05
  • 如何使用日期和時間物件來確定 PHP 中的時間邊界?
    如何使用日期和時間物件來確定 PHP 中的時間邊界?
    確定PHP 中的時間邊界在此編程場景中,我們的任務是確定給定時間是否在預先定義的範圍內。具體來說,我們得到三個時間字串:當前時間、日出和日落。我們的目標是確定當前時間是否位於日出和日落的邊界時間之間。 為了應對這個挑戰,我們將使用 DateTime 類別。這個類別使我們能夠表示和操作日期和時間。我們...
    程式設計 發佈於2024-11-05
  • 如何使用 CSS 變換比例修復 jQuery 拖曳/調整大小問題?
    如何使用 CSS 變換比例修復 jQuery 拖曳/調整大小問題?
    jQuery 使用CSS 轉換縮放拖曳/調整大小問題: 當應用CSS 轉換時,特別是變換:矩陣(0.5, 0, 0, 0.5, 0, 0);,對於一個div 並在子元素上使用jQuery 的draggable() 和resizing() 插件,jQuery 所做的更改變得與滑鼠位置「不同步”。 解決...
    程式設計 發佈於2024-11-05
  • 如何修復 TensorFlow 中的「ValueError:無法將 NumPy 陣列轉換為張量(不支援的物件類型浮點)」錯誤?
    如何修復 TensorFlow 中的「ValueError:無法將 NumPy 陣列轉換為張量(不支援的物件類型浮點)」錯誤?
    TensorFlow:解決「ValueError: Failed to Convert NumPy Array to Tensor (Unsupported Object Type Float)」工作時遇到的常見錯誤TensorFlow 的錯誤是「ValueError:無法將NumPy 陣列轉換為T...
    程式設計 發佈於2024-11-05
  • 如何有效率判斷本機儲存項目是否存在?
    如何有效率判斷本機儲存項目是否存在?
    確定本地儲存專案是否存在使用 Web 儲存時,在存取或修改特定專案之前驗證它們是否存在至關重要。在本例中,我們想要確定 localStorage 中是否設定了特定項目。 當前方法檢查項目是否存在的當前方法似乎是:if (!(localStorage.getItem("infiniteScr...
    程式設計 發佈於2024-11-05
  • Java 中的原子是什麼?了解 Java 中的原子性和線程安全
    Java 中的原子是什麼?了解 Java 中的原子性和線程安全
    1. Java 原子簡介 1.1 Java 中什麼是原子? 在Java中,java.util.concurrent.atomic套件提供了一組支援對單一變數進行無鎖定線程安全程式設計的類別。這些類別統稱為原子變數。最常使用的原子類別包括 AtomicInteger ...
    程式設計 發佈於2024-11-05

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

Copyright© 2022 湘ICP备2022001581号-3