Skip to content

Instantly share code, notes, and snippets.

@HeNy007
Created February 19, 2022 13:16
Show Gist options
  • Select an option

  • Save HeNy007/56ad68136e7f07c7d85c1835ed3a709c to your computer and use it in GitHub Desktop.

Select an option

Save HeNy007/56ad68136e7f07c7d85c1835ed3a709c to your computer and use it in GitHub Desktop.
Dark theme toggle button
<div>
<input type="checkbox" class="checkbox" id="checkbox">
<label for="checkbox" class="label">
<i class="fas fa-moon"></i>
<i class='fas fa-sun'></i>
<div class='ball'>
</label>
</div>
const checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', ()=>{
document.body.classList.toggle('dark');
})
* {
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
transition: background 0.2s linear;
}
body.dark {
background-color: #292c35;
}
.checkbox {
opacity: 0;
position: absolute;
}
.label {
width: 50px;
height: 26px;
background-color:#111;
display: flex;
border-radius:50px;
align-items: center;
justify-content: space-between;
padding: 5px;
position: relative;
transform: scale(1.5);
}
.ball {
width: 20px;
height: 20px;
background-color: white;
position: absolute;
top: 2px;
left: 2px;
border-radius: 50%;
transition: transform 0.2s linear;
}
/* target the elemenent after the label*/
.checkbox:checked + .label .ball{
transform: translateX(24px);
}
.fa-moon {
color: pink;
}
.fa-sun {
color: yellow;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment