Dark mode toggle button without javascript – part 2

Written by Lucie Zdeňková on 2025-01-16

htmlcss

DraftIntro....


#tady bude část 2, stylování samotného togglu, pokud se předchozí schválí

Toggle button UI

Following CSS code defines user interface and behaviour of the toggle. Variable properties, e.g. background-color: var(--toggle-bg) are dynamically updated based on the state of the toggle or the user’s system preferences, allowing for a smooth transition between light and dark modes. Illustrations of sun and moon are implemented as backgroud svg images of <span class="sun"> element. Those illustrations were downloaded from UXWING.

label.darkmode-label {
    width: 100px;
    height: 40px;
    position: relative;
    display: block;
    border-radius: 40px;
    box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.4), inset 0px -1px 3px rgba(255, 255, 255, 0.4);
    cursor: pointer;
    background-color: var(--toggle-bg);
}

label.darkmode-label:after {
    content: "";
    width: 36px;
    height: 36px;
    position: absolute;
    top: 2px;
    left: var(--label-left);
    background: linear-gradient(180deg, var(--gradient-bg1), var(--gradient-bg2));
    border-radius: 36px;
    box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
    transform: var(--transformantion);
}

input#darkmode-toggle {
    width: 0;
    height: 0;
    visibility: hidden;
    display: none;
}

label.darkmode-label,
label.darkmode-label:after {
    transition: 0.3s
}

label.darkmode-label:active:after {
    width: 52px;
}

label.darkmode-label div {
    position: absolute;
    width: 24px;
    height: 24px;
    top: 8px;
    z-index: 100;
}

label.darkmode-label span.sun {
    display: block;
    width: 24px;
    height: 24px;
    background-image: var(--img-sun);
    transition: 0.3s;
    position: absolute;
    z-index: 1;
    left: 8px;
    top: 8px;
}

label.darkmode-label span.moon {
    display: block;
    width: 24px;
    height: 24px;
    background-image: var(--img-moon);
    transition: 0.3s;
    position: absolute;
    z-index: 1;
    left: 68px;
    top: 8px;
}

This is everyting you need to implement dark mode toggle on the static website without the need to use javascript.

Thank you for reading and see ya next time!

Resources:

  1. CSS Dark Mode Toggle Button from scratch in 6 Minutes
  2. An HTML and CSS only dark-mode toggle button