Logo

Snippets that build the web.

Snippet Information

Title: Dark Mode Toggle

Description: Light Mode and Dark Mode toggle. For larger projects SASS/LESS would make managing styles a lot easier.

Tags: html, css, js

Author: danc0

View Demo

Snippet Body

View HTML expand_more

Copy Code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
        <div class="toggle-mode">
            <span class="toggle">
                <span class="switch"></span>
            </span>
        </div>
    </nav>
    <script src="main.js"></script>
</body>
</html>

View CSS expand_more

Copy Code
/* Base Styling */
*{
    padding:0;
    margin:0;
    box-sizing: border-box;
}

body{
    transition:all .3s ease-in-out;
    background:#f8f8f8;
    font-family: Arial, Helvetica, sans-serif;
}

body nav{
    display:flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding:10px;
}

body nav ul{
    display:flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-evenly;
    list-style-type: none;
}

body nav ul li{
    margin-right:20px;
}
/* Toggle UI */
.toggle{
    display:block;
    content: ' ';
    width:60px;
    height:30px;
    border-radius:9999px;
    border:1px solid rgb(95, 146, 167);
    position:relative;
    background:skyblue;
}

.toggle:hover{
    cursor: pointer;
}

.toggle .switch{
    height:20px;
    width:20px;
    border-radius:50%;
    position:absolute;
    top:2.5px;
    left:5px;
    background:linear-gradient(45deg, rgb(255, 174, 0) 0%, yellow 100%);
    transition:all .5s ease-in-out;
}

.toggle.dark{
    background:#2c2b2b;
    border:1px solid #111111;
    box-shadow: inset 0 -10px 20px rgba(95, 95, 95, 0.5);
}
.toggle.dark .switch {
    background:linear-gradient(45deg, rgb(61, 61, 61) 0%, #ccc 100%);
    left:calc(100% - 25px);
}

/* LIGHT Mode */

body nav ul li a {
    color:#2c2b2b;
    font-weight:700;
    text-decoration: none;
}

/* DARK Mode */
body[dark] {
    background:#252525;
}

body[dark] nav ul li a {
    color:#fff;
    font-weight:700;
    text-decoration: none;
}

View JS expand_more

Copy Code
(() => {
    const toggle = document.querySelector('.toggle')

    toggle.addEventListener('click', e => {
        toggle.classList.toggle('dark')
        document.querySelector('body').toggleAttribute('dark')
    })
})()