Skip to content

Instantly share code, notes, and snippets.

@hexaaagon
Created May 9, 2023 10:32
Show Gist options
  • Select an option

  • Save hexaaagon/1ea63e4caf80095eb999ec410df8f4d9 to your computer and use it in GitHub Desktop.

Select an option

Save hexaaagon/1ea63e4caf80095eb999ec410df8f4d9 to your computer and use it in GitHub Desktop.
Light/Dark Theme Toggle using CSS and Javascript
<h1>Light/Dark Toggle<br> Button</h1>
<div>
<input type="checkbox" class="checkbox" id="checkbox">
<label for="checkbox" class="checkbox-label">
<i class="fas fa-moon"></i>
<i class="fas fa-sun"></i>
<span class="ball"></span>
</label>
</div>
const checkbox = document.getElementById("checkbox")
checkbox.addEventListener("change", () => {
document.body.classList.toggle("dark")
})
@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");
* {box-sizing: border-box;}
body {
font-family: "Montserrat", sans-serif;
background-color: #fff;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
text-align: center;
min-height: 100vh;
margin: 0;
transition: background 0.2s linear;
}
body.dark {background-color: #111319;} /* #9b59b6 */
body.dark h1, body.dark .support a {color: #fff;}
.checkbox {
opacity: 0;
position: absolute;
}
.checkbox-label {
background-color: #111;
width: 50px;
height: 26px;
border-radius: 50px;
position: relative;
padding: 5px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
}
.fa-moon {color: #f1c40f;}
.fa-sun {color: #f39c12;}
.checkbox-label .ball {
background-color: #fff;
width: 22px;
height: 22px;
position: absolute;
left: 2px;
top: 2px;
border-radius: 50%;
transition: transform 0.2s linear;
}
.checkbox:checked + .checkbox-label .ball {
transform: translateX(24px);
background-color: #111319;
}
.checkbox:checked + .checkbox-label {
background-color: #fff;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment