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

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]删除
最新教程 更多>
  • 插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于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
  • 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
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-12-26
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSocke...
    编程 发布于2024-12-26
  • 除了“if”语句之外:还有什么地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有什么地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于2024-12-26
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-12-26
  • 尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    解决 PHP 中的 POST 请求故障在提供的代码片段中:action=''而不是:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"检查 $_POST数组:表单提交后使用 var_dump 检查 $_POST 数...
    编程 发布于2024-12-26
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1和$array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求是构...
    编程 发布于2024-12-26
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-12-26
  • 如何在 PHP 中转换所有类型的智能引号?
    如何在 PHP 中转换所有类型的智能引号?
    在 PHP 中转换所有类型的智能引号智能引号是用于代替常规直引号(' 和 ")的印刷标记。它们提供了更精致和然而,软件应用程序通常会在不同类型的智能引号之间进行转换,从而导致不一致。智能引号中的挑战转换转换智能引号的困难在于用于表示它们的各种编码和字符,不同的操作系统和软件程序采用...
    编程 发布于2024-12-26
  • 循环 JavaScript 数组有哪些不同的方法?
    循环 JavaScript 数组有哪些不同的方法?
    使用 JavaScript 循环遍历数组遍历数组的元素是 JavaScript 中的一项常见任务。有多种方法可供选择,每种方法都有自己的优点和局限性。让我们探讨一下这些选项:数组1。 for-of 循​​环 (ES2015 )此循环使用迭代器迭代数组的值:const arr = ["a&q...
    编程 发布于2024-12-26
  • 如何在 Python 中有效地暂停 Selenium WebDriver 执行?
    如何在 Python 中有效地暂停 Selenium WebDriver 执行?
    Selenium WebDriver 中的等待和条件语句问题: 如何在 Python 中暂停 Selenium WebDriver 执行几毫秒?答案:虽然time.sleep() 函数可用于暂停执行指定的秒数,在 Selenium WebDriver 自动化中一般不建议使用。使用 Selenium ...
    编程 发布于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

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

Copyright© 2022 湘ICP备2022001581号-3