Categories
Web Design Web Development

Simple CSS Form Checkbox Toggle

The HTML checkbox input is one of the oldest elements to be introduced to HTML. So it’s no surprise that I’m tired of looking at them. But the element is crucial to forms and not going away any time soon. I prefer the look and feel of toggle switches, possibly because of the iOS toggles so commonly used.

There was a time when you needed Javascript to assist with the animation and handling of this style of toggle. No longer. Below is a simple and elegant CSS only solution to handling the toggle.

Sample CSS Toggle Button:

Simple HTML Checkbox Toggle

<div class="toggle-wrapper">
  <input class="toggle-input" type="checkbox" id="my-field-id" name="my-field" value="true" />
  <label for="my-field-id" class="toggle-button"><span>My Label Text</span></label>
</div>

Simple CSS Checkbox Toggle

.toggle-wrapper {
    position: relative;
}
input.toggle-input,
label.toggle-button > span {
    position: absolute;
    left: -9999px;
}
label.toggle-button {
    background: #c87074;
    border-radius: 12px;
    cursor: pointer;
    display: inline-block;
    height: 24px;
    width: 50px;
}
label.toggle-button:before {
    background: #fff;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    content: ' ';
    display: block;
    height: 20px;
    width: 20px;
    position: absolute;
    top: 2px;
    left: 2px;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    -o-transition: all 200ms ease;
    transition: all 200ms ease;
}
input.toggle-input:checked ~ label.toggle-button {
    background: green;
}
input.toggle-input:checked ~ label.toggle-button:before {
    -webkit-transform: translate(26px, 0);
    -moz-transform: translate(26px, 0);
    -ms-transform: translate(26px, 0);
    -o-transform: translate(26px, 0);
    transform: translate(26px, 0);
}

That’s it! It works like magic. I love using this checkbox toggle for forms that turn modules or features on and off.

By Tim Bunch

Tim Bunch is a Web Developer from Rockaway Beach, Oregon. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply