Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bishoplee/b10987b434fc501d004eb888c90e7517 to your computer and use it in GitHub Desktop.
Save bishoplee/b10987b434fc501d004eb888c90e7517 to your computer and use it in GitHub Desktop.
CSS grid toggle (animates in Firefox Nightly only)

CSS grid toggle (animates in Firefox Nightly only)

A new take on the CSS toggle, using CSS grid animations. See code for explanations :)

A Pen by Liam on CodePen.

License.

<label class="switch-wrap">
<input type="checkbox" />
<div class="switch"></div>
</label>
//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