<label class="switch">
<input class="switch__input" type="checkbox" data-theme-toggle>
<span class="switch__slider"></span>
</label>
* {
margin: 0;
padding: 0;
border: none;
outline: none;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html,
body {
height: 100%;
}
:root {
--color-1: #040404;
--color-2: #f9f9f9;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: var(--color-1);
transition: background 0.6s;
}
.switch {
position: relative;
display: inline-block;
width: 3.8rem;
height: 2rem;
}
.switch__input {
opacity: 0;
width: 0;
height: 0;
}
.switch__slider {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #ff4754;
border-radius: 1rem;
transition: background 0.2s;
cursor: pointer;
}
.switch__slider::before {
content: "";
position: absolute;
left: 0.2rem;
top: 50%;
transform: translateY(-50%);
height: 1.6rem;
width: 1.6rem;
border-radius: 1.6rem;
background: var(--color-1);
transition: transform 0.2s, width 0.2s, background 0.2s;
}
.switch__input:checked + .switch__slider {
background: var(--color-2);
}
.switch__input:not(:checked):active + .switch__slider::before {
width: 2.4rem;
}
.switch__input:checked:active + .switch__slider::before {
transform: translate(1rem, -50%);
width: 2.4rem;
}
.switch__input:checked + .switch__slider::before {
transform: translate(1.8rem, -50%);
}
const stylesheet = document.documentElement.style;
const toggle = document.querySelector(".switch__input[data-theme-toggle]");
toggle.addEventListener("click", () => {
// get the css variables
const color1 = getComputedStyle(document.documentElement).getPropertyValue(
"--color-1"
);
const color2 = getComputedStyle(document.documentElement).getPropertyValue(
"--color-2"
);
// switching the css variables
stylesheet.setProperty("--color-1", color2);
stylesheet.setProperty("--color-2", color1);
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.