DEV Community 👩‍💻👨‍💻

Cover image for How to toggle dark mode
Yigit S
Yigit S

Posted on

How to toggle dark mode

Hi all. In this post, I'll show you how to create a toggle button to switch between dark and light mode.


<!DOCTYPE html>
<html lang="en" data-theme ="light">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, 

    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>


    <div class="toggle-container">
        <input type="checkbox" id="toggle" name="toggle">
        <label for="toggle"></label>

    <h1>Long Live Rock 'n Roll</h1>
    <p>Rock and Roll ain't noise pollution!
Rock and Roll will never die!
I like that old time Rock and Roll!</p>

Enter fullscreen mode Exit fullscreen mode


    box-sizing: border-box;

    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;

    min-height: 100vh;
    flex-direction: column;
    padding: 5rem;
    transition: background 0.4s linear, color 0.4s linear;
    font-size: 2rem;

    background: #201e1e;
    color: white;

    user-select: none;
    cursor: pointer;
    background-color: #201e1e;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: inline-block;
    transition: background 0.4s linear;

body.dark label{
    background-color: #ffff;

    position: fixed;
    top: 10px;

    visibility: hidden;
Enter fullscreen mode Exit fullscreen mode


const toggle = document.getElementById("toggle")

toggle.addEventListener('change', (e)=>{


Enter fullscreen mode Exit fullscreen mode

Final Result

I hope you find this tutorial useful. See you on the next article.
Here's the Source Code on GitHub
Here's the YouTube Video where I code it from scratch.
Check it out on CodePen

Follow me on

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now