Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active July 2, 2023 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/f5d36e4c038f986a3f5ddf18b6ca4266 to your computer and use it in GitHub Desktop.
Save yairEO/f5d36e4c038f986a3f5ddf18b6ca4266 to your computer and use it in GitHub Desktop.
checkbox-switch.css

Checkbox-Switch

CSS-only styles for transforming an innocent input of type checkbox to a beautiful switch
which so many desire to have in their UX. Automatically looks great in RTL direction.

See Demo

switch

📦 Install

npm i -S gist:f5d36e4c038f986a3f5ddf18b6ca4266

How to use

Import or include in some way the CSS file so it applies globally:

Example (when installed in /node_modules):

import 'checkbox-switch`

Simply add role='switch' to your input element to apply the styles:

<input type='checkbox' role='switch'/>

Or with a label:

<label>
  <input type='checkbox' role='switch'/>
  Toggle Me
</label>
label:has([role=switch]) {
zoom: var(--switch-zoom, 1);
display: inline-flex;
align-items: center;
gap: 1em;
cursor: pointer;
user-select: none;
}
input[role=switch] {
--switch-handle-size: 8px;
--switch-bg-size: 24px;
--switch-handle-gap: 3px;
--switch-fg: #3c79fc;
--switch-bg: color-mix(in srgb, var(--switch-fg) 20%, transparent);
appearance: none;
-webkit-appearance: none;
box-sizing: content-box;
display: inline-flex;
padding-inline: 0 var(--switch-bg-size);
border: none;
height: auto;
width: auto;
font-size: 0;
margin: 0;
border-radius: 100px;
background: var(--switch-bg);
transition: var(--switch-duration, .2s) cubic-bezier(.65, 0, .5, 1);;
user-select: none;
outline: none;
filter: grayscale(1); /* de-colorize the switch */
cursor: pointer;
}
input[role=switch]:checked {
padding-inline: var(--switch-bg-size) 0;
filter: none;
}
input[role=switch]::before {
content: '';
padding: var(--switch-handle-size);
margin: var(--switch-handle-gap);
background: var(--switch-fg);
border-radius: 50%;
transition: inherit;
}
{
"version": "1.0.1",
"name": "checkbox-switch",
"main": "checkbox-switch.css",
"author": "Yair Even Or <vsync.design@gmail.com> (https://github.com/yairEO)",
"description": "CSS-only styles for transforming an innocent input of type 'checkbox' to a beautiful switch toggler"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment