Implement Dark Mode in Websites Using HTML CSS & JavaScript (original) (raw)

Last Updated : 06 Feb, 2025

Dark and light modes let users switch between a dark background with light text and a light background with dark text, making websites more comfortable and accessible based on their preferences or surroundings.

What We’re Going to Create

Project Preview

Screenshot-2025-01-21-162140

How to Make Dark Mode for Websites using HTML CSS & JavaScript ?

Implement Dark Mode in Websites -HTML and CSS code

This is the basic structure of the webpage. The page will feature a button to toggle between dark and light modes.

HTML `

Welcome to Dark/Light Mode Toggle

This page demonstrates a simple yet powerful way to switch between dark and light modes for a better user experience.

Switching to dark mode can reduce eye strain, especially in low-light environments, while light mode is better for bright settings.

Switch to Dark Mode

Benefits of Dark/Light Mode

Learn more about web accessibility and user experience on the W3C Accessibility Guidelines.

`

**In this example

Implement Dark Mode in Websites - JavaScript code

This JavaScript enables dark/light mode toggling by dynamically switching classes and updating the button text using classList.replace().

JavaScript `

const toggleButton = document.getElementById('theme-toggle'); const body = document.body;

body.classList.add('light-mode');

toggleButton.addEventListener('click', () => { if (body.classList.contains('light-mode')) { body.classList.replace('light-mode', 'dark-mode'); toggleButton.textContent = 'Switch to Light Mode'; } else { body.classList.replace('dark-mode', 'light-mode'); toggleButton.textContent = 'Switch to Dark Mode'; } });

`

**In this example

Complete code

HTML `

Welcome to Dark/Light Mode Toggle

This page demonstrates a simple yet powerful way to switch between dark and light modes for a better user experience.

Switching to dark mode can reduce eye strain, especially in low-light environments, while light mode is better for bright settings.

Switch to Dark Mode

Benefits of Dark/Light Mode

Learn more about web accessibility and user experience on the W3C Accessibility Guidelines.