The light and dark modes are a feature in the web browser that lets you choose between a white screen or a black screen. The light mode is easier on the eyes and it is great for reading at night. The dark mode, on the other hand, is great for working with images and videos during the day.
This tutorial will show you how to add light and dark modes to your website’s template. You can use this tutorial to add light and dark modes to your site’s design.
If you follow this post you can easily understand how to add Light & Dark mode on Template.
Step 01: HTML Code :
<!doctype html> <html lang="zxx" class="theme-light"> <head> <link rel="stylesheet" href="assets/css/dark.css"> </head> <body> <!-- dark version --> <div class="dark-version"> <label id="switch" class="switch"> <input type="checkbox" onchange="toggleTheme()" id="slider"> <span class="slider round"></span> </label> </div> <!-- dark version --> </body> </html>
Step 02: CSS Code :
// dark version switch css .dark-version { position: fixed; z-index: 1; right: 95px; bottom: 45px; .switch { position: relative; display: inline-block; width: 60px; height: 34px; input { opacity: 0; width: 0; height: 0; } } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background: $main-gradient-color; transition: 0.4s; &:before { position: absolute; content: ""; height: 30px; width: 30px; left: 2.5px; bottom: 4px; top: 0; bottom: 0; margin: auto 0; -webkit-transition: 0.4s; transition: 0.4s; box-shadow: 0 0px 15px #2020203d; background: white url('https://i.ibb.co/FxzBYR9/night.png'); background-repeat: no-repeat; background-position: center; } } input:checked + .slider { background-color: $main-color; } input:focus + .slider { box-shadow: 0 0 1px $main-color; } input:checked + .slider:before { -webkit-transform: translateX(24px); -ms-transform: translateX(24px); transform: translateX(24px); background: white url('https://i.ibb.co/7JfqXxB/sunny.png'); background-repeat: no-repeat; background-position: center; } .slider { &.round { border-radius: 50px; &:before { border-radius: 50%; } } } } // Dark & Light CSS .theme-light { } .theme-dark { }
Step 03: JavaScript Code :
// function to set a given theme/color-scheme function setTheme(themeName) { localStorage.setItem('theme', themeName); document.documentElement.className = themeName; } // function to toggle between light and dark theme function toggleTheme() { if (localStorage.getItem('theme') === 'theme-dark') { setTheme('theme-light'); } else { setTheme('theme-dark'); } } // Immediately invoked function to set the theme on initial load (function () { if (localStorage.getItem('theme') === 'theme-dark') { setTheme('theme-dark'); document.getElementById('slider').checked = false; } else { setTheme('theme-light'); document.getElementById('slider').checked = true; } })();
If you have any queries, please let me know in the comments section.
Happy Coding!
Leave a Reply