DEV Community

Cover image for Learn how to add a simple dark/light mode switcher!
CristoferK
CristoferK

Posted on

Learn how to add a simple dark/light mode switcher!

Don't forget to subscribe to my YouTube channel! https://www.youtube.com/channel/UCFzeA3xC-_i4ZT-XwcwsJxQ/featured


HTML

<!DOCTYPE html>
<html>
<head>
    <title>Light/Dark mode</title>
</head>
<body>
<header>
    <label id="dark-change"></label>

<style>
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
main {
    margin: Svh 15%;
        align-content: center;
    align-items: center;
}
h1 {
    font-size: 40px;
    font-weight: 400;
    text-align: center;
}
img {
    width: 50%;
    height: auto;
}
p {
    text-align: justify;
    font-size: 18px;
}
label {
    position: absolute;
    width: 45px;
    height: 22px;
    right: 20px;
    top: 20px;
    border: 2px solid;
    border-radius: 20px;
}
label:before {
    position: absolute;
    content: "";
    width: 20px;
    height: 20px;
    left: 1px;
    top: 1px;
    border-radius: 50%;
    cursor: pointer;
    background: #000;
    transition: 0.4s;
}
label.active:before {
    left: 24px;
    background: #fff;
}
body.night {
    background: #000;
    color: #fff;
    transition: 0.5s;
}
</style>
</header>
<main>
    <h1>Easy Light/Dark mode</h1>
    <div id="respon">
        <img src="https://www.universityofcalifornia.edu/sites/default/files/night-sky-purple.jpg">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec malesuada tortor. Ut pharetra, velit ut facilisis scelerisque, tortor ligula imperdiet metus, et ultrices nisi erat at enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris vestibulum et erat in ultricies. Vivamus id nulla elementum, sagittis felis id, aliquet ligula.</p>
    </div>
</main>
<script>
var content = document.getElementsByTagName('body')[0];
var darkMode = document.getElementById('dark-change');
darkMode.addEventListener('click', function() {
        darkMode.classList.toggle('active');
        content.classList.toggle('night');
})
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)