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
浏览:723

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如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 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 ConnectDB...
    编程 发布于2024-11-05
  • 测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    编程 发布于2024-11-05
  • 我对 DuckDuckGo 登陆页面的看法
    我对 DuckDuckGo 登陆页面的看法
    “你为什么不谷歌一下呢?”是我在对话中得到的常见答案。谷歌的无处不在甚至催生了新的动词“谷歌”。但是我编写的代码越多,我就越质疑我每天使用的数字工具。也许我对谷歌使用我的个人信息的方式不再感到满意。或者我们很多人依赖谷歌进行互联网搜索和其他应用程序,说实话,我厌倦了在搜索某个主题或产品后弹出的广告,...
    编程 发布于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 POSTs尝试使用 multipart/form-data POST 数据时,可能会出现类似所提供的错误消息遭遇。理解问题需要检查问题的构成。遇到的错误是 301 Moved Permanently 响应,表明资源已被永久重定向。当未为 multipart/f...
    编程 发布于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 数组转换为...
    编程 发布于2024-11-05
  • 如何高效判断本地存储项是否存在?
    如何高效判断本地存储项是否存在?
    确定本地存储项目是否存在使用 Web 存储时,在访问或修改特定项目之前验证它们是否存在至关重要。在本例中,我们想要确定 localStorage 中是否设置了特定项目。当前方法检查项目是否存在的当前方法似乎是:if (!(localStorage.getItem("infiniteScro...
    编程 发布于2024-11-05
  • Java 中的原子是什么?了解 Java 中的原子性和线程安全
    Java 中的原子是什么?了解 Java 中的原子性和线程安全
    1. Java 原子简介 1.1 Java 中什么是原子? 在Java中,java.util.concurrent.atomic包提供了一组支持对单个变量进行无锁线程安全编程的类。这些类统称为原子变量。最常用的原子类包括 AtomicInteger 、 Atomic...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3