Create CSS Toggle Switches

CSS has come a long way. You can now create toggle switches, among other awesome things, with just plain CSS.

This article will show you how you can create cool mobile-looking toggle switches by using just strictly CSS.

The HTML

< input type = " checkbox " id = " toggle " class = " offscreen " /> < label for = " toggle " class = " switch " > </ label >

The CSS

.switch { position : relative ; display : inline-block ; width : 40px ; height : 20px ; background-color : rgba ( 0, 0, 0, 0.25 ) ; border-radius : 20px ; transition : all 0.3s ; } .switch::after { content : '' ; position : absolute ; width : 18px ; height : 18px ; border-radius : 18px ; background-color : white ; top : 1px ; left : 1px ; transition : all 0.3s ; } input[type='checkbox']:checked + .switch::after { transform : translateX ( 20px ) ; } input[type='checkbox']:checked + .switch { background-color : #7983ff ; } .offscreen { position : absolute ; left : -9999px ; }

This effect is styling only the <label> element to look like a toggle switch, and hiding the actual <input> checkbox by positioning it offscreen. When clicking the label associated with the <input> element, it sets the <input> checkbox into the :checked state.