A new take on the CSS toggle, using CSS grid animations. See code for explanations :)
Created
January 30, 2019 07:30
-
-
Save bishoplee/b10987b434fc501d004eb888c90e7517 to your computer and use it in GitHub Desktop.
CSS grid toggle (animates in Firefox Nightly only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<label class="switch-wrap"> | |
<input type="checkbox" /> | |
<div class="switch"></div> | |
</label> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//HOW THIS WORKS: | |
//The 0fr column takes up no space (yet). | |
//The two 1fr columns are the toggle nub(??), and the ~visible~ empty space. | |
//When checked, the left column becomes 1fr and the right column becomes 0fr, creating the effect of the nub moving. | |
//==================== | |
//Change width or padding values freely :) | |
//But for the 'nub' to look perfectly circular (at 1fr, i.e. 50%), the toggle's height must be half its width, plus the padding value | |
$width: 120px; | |
$padding: 7px; | |
$height: $width / 2 + $padding; | |
//boring layout stuff: | |
html { box-sizing: border-box; height: 100% } *, *::before, *::after { box-sizing: inherit; } | |
body {display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #f5f5f5; } | |
//toggle code begins! | |
.switch-wrap { | |
cursor: pointer; | |
background: #15273b; | |
padding: $padding; | |
width: $width; | |
height: $height; | |
border-radius: $height / 2; | |
input { | |
position: absolute; | |
opacity: 0; | |
width: 0; | |
height: 0; | |
} | |
} | |
.switch { | |
height: 100%; | |
display: grid; | |
grid-template-columns: 0fr 1fr 1fr; | |
transition: .2s; | |
//ICYMI, pseudo elements are treated as grid items | |
&::after { | |
content: ''; | |
border-radius: 50%; | |
background: #ccc; | |
grid-column: 2; | |
transition: background .2s; | |
} | |
} | |
input:checked { | |
+ .switch { | |
grid-template-columns: 1fr 1fr 0fr; | |
&::after { | |
background-color: #52cf71; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment