toggle-switch css checkbox

Turn checkboxes into nice toggle-switches

by Ayyappan Sakthivadivel

HTML

Square
<input type="checkbox" class="toggle-switch square">

SCSS

@mixin toggle-switch($toggleWidth, $toggleHeight, $handleMargin, $roundness, $on-color, $off-color) {
    
    $handleColor: #FFF;
    $handleHeight: $toggleHeight - ($handleMargin * 2);
    $handleWidth: $handleHeight;
    $handleRadius: $handleHeight * $roundness;
    $toggleRadius: ($toggleHeight / 2) * $roundness;
    
    position: relative;
    display: block;

    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;

    top: 0;
    left: 0;
    width: $toggleWidth;
    height: $toggleHeight;
    margin: 5px;
    border-radius: $toggleRadius;
    background: $off-color;
    box-sizing: border-box;
    box-shadow: inset 0px 1px 0px rgba(0,0,0,0.2);
    // text-indent: -9999px;

    cursor: pointer;

    //toggle when checked
    &:checked {
        background: $on-color;
        //border-color: $on-color;
    }

    //handle
    &:after {
        position: absolute;
        @if $roundness < 0.5 { content: '|||'; } @else { content: ''; }
        text-align: center;
        color: rgba(0,0,0,0.1);
        top: $handleMargin;
        left: $handleMargin;
        width: $handleWidth;
        height: $handleHeight;
        border-radius: ($handleRadius / 2);
        transition: 0.3s;
        background: $handleColor;

        box-shadow: 0px 1px 0px 1px rgba(0,0,0,0.25);
    }
    //handle when checked
    &:checked:after {
        left: calc(100% - #{$handleMargin});
        transform: translateX(-100%);
    }

    //handdle when pressed down
    &:active:after {
        width: $handleWidth * 1.5;
    }
    
}

//create your own classes as you wish
input[type="checkbox"].toggle-switch.square {
	@include toggle-switch(32px, 16px, 1px, 0.1, blue, gray);
}