If you want to allow users to allow preference for dark and light mode, you can use the below given examples.
Firstly, save the below file as index.html and add the HTML content. It also contains links to css style and script js files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dark and Light Mode</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Dark and Light Mode Example</h1> <button id="themeToggle">Toggle Theme</button> </div> <script src="script.js"></script> </body> </html> |
The below file contains the CSS for dark and light mode. The below example CSS code apply CSS to classes based on dark and light mode. Save the below file as ‘styles.css‘.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
/* Default Light Theme */ :root { --bg-color: #ffffff; --text-color: #000000; --button-bg: #eeeeee; --button-text: #000000; } /* Dark Theme Variables */ body.dark-mode { --bg-color: #121212; --text-color: #ffffff; --button-bg: #333333; --button-text: #ffffff; } /* Apply Variables */ body { background-color: var(--bg-color); color: var(--text-color); font-family: Arial, sans-serif; margin: 0; padding: 2rem; transition: background-color 0.3s, color 0.3s; } button { background-color: var(--button-bg); color: var(--button-text); border: none; padding: 0.5rem 1rem; cursor: pointer; transition: background-color 0.3s, color 0.3s; } |
The JS script contains the code to toggle the dark and light mode. In addition to this, it also save the preference using browser local storage. Save the below file as ‘script.js‘.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const body = document.body; const toggleBtn = document.getElementById("themeToggle"); // Load saved theme if (localStorage.getItem("theme") === "dark") { body.classList.add("dark-mode"); } toggleBtn.addEventListener("click", () => { body.classList.toggle("dark-mode"); const theme = body.classList.contains("dark-mode") ? "dark" : "light"; localStorage.setItem("theme", theme); }); |
You can combine these file to create a page with dark and light mode feature.