CSS Checkbox Styling

Custom styles for checkboxes using CSS only

by bizamajig

HTML

<div>
    <input type=checkbox name=checkbox1 value=1 id=checkbox1 />
    <label for=checkbox1 class=cb-label>Some kind of label for this shizzle</label>
</div>

<div>
    <input type=checkbox name=checkbox2 value=1 id=checkbox2 checked=checked />
    <label for=checkbox2 class=cb-label>Another kind of label for this shizzle</label>
</div>

CSS

/* Tidy ups */
body {
    padding: 50px;
}
label {
    cursor: pointer;
}
div {
    margin-bottom: 50px;
}

/* Checkbox */
input[type="checkbox"] {
    /* IE opacity hacks */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
    opacity: 0;
    margin-left: 100px;
}
.cb-label {
    position: relative;
}
.cb-label:before {
    content: ' ';
    position: absolute;
    background: transparent url(http://blog.parkji.co.uk/images/posts/styling-checkboxes/switch.jpg) no-repeat scroll 0 0;
    height: 41px;
    width: 143px;
    left: -150px
}
input[type="checkbox"]:checked ~ .cb-label:before,
/* the .checked class is used by IE only */
input[type="checkbox"].checked ~ .cb-label:before {
    background-position: 0 -40px;
}

JavaScript

// Some debug  and IE stuff, not needed in a decent browser, but uncomment to check stuff
/*
$(function() {
    $('input[type="checkbox"]').change(function() {
        alert(this.checked);
    });
    
    // For IE
    $('input[type="checkbox"]').change(function() {
        $(this).toggleClass('checked');
    });
});
*/