<h1>Accessible toggle checkbox</h1> <br> <style> .toggle { position: relative; } .toggle *, .toggle *:before, .toggle *:after { box-sizing: border-box; } .toggle input[type=checkbox] { opacity: 0; position: absolute; top: 0; left: 0; padding: 0; } .toggle input[type=checkbox]:focus ~ label .toggle__switch, .toggle input[type=checkbox]:hover ~ label .toggle__switch { background-color: #444; } .toggle input[type=checkbox]:checked:focus ~ label .toggle__switch, .toggle input[type=checkbox]:checked:hover ~ label .toggle__switch { background-color: #34690c; } .toggle input[type=checkbox]:checked ~ label .toggle__switch { background-color: #529c1a; } .toggle input[type=checkbox]:checked ~ label .toggle__switch:before { content: attr(data-unchecked); left: 0; } .toggle input[type=checkbox]:checked ~ label .toggle__switch:after { transform: translate3d(28px, 0, 0); color: #34690c; content: attr(data-checked); } .toggle label { user-select: none; position: relative; display: flex; align-items: center; } .toggle label .toggle__label-text { font-size: 1rem; padding-right: 30px; } .toggle .toggle__switch { font-size: 10px; height: 30px; -webkit-box-flex: 0; flex: 0 0 60px; border-radius: 30px; transition: background-color 0.3s cubic-bezier(0.86, 0, 0.07, 1); background: #636060; position: relative; } .toggle .toggle__switch:before { left: 30px; font-size: 10px; line-height: 30px; width: 30px; padding: 0 4px; color: #e6e6e6; content: attr(data-checked); position: absolute; top: 0; text-transform: uppercase; text-align: center; } .toggle .toggle__switch:after { font-weight: 700; top: 2px; left: 2px; border-radius: 15px; width: 28px; line-height: 26px; font-size: 10px; transition: transform 0.3s cubic-bezier(0.86, 0, 0.07, 1); color: #34690c; content: attr(data-unchecked); position: absolute; z-index: 5; text-transform: uppercase; text-align: center; background: white; transform: translate3d(0, 0, 0); } </style> <div class="toggle"> <input id="toggle-demo" type="checkbox"> <label for="toggle-demo"> <div class="toggle__label-text">Toggle Me</div> <div class="toggle__switch" data-checked="Yes" data-unchecked="No"></div> </label> </div>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter