Styling a checkbox using CSS3

Got this idea from tutsplus but found a problem with iPad so just wanted to save it on my blog:

Taking advantage of the “:checked” selector at CSS3 we can now style a checkbox using this:

input[type="checkbox"] {display:none;}
    input[type="checkbox"] + label .fakeCheckbox {
        display:inline-block; cursor:pointer; vertical-align:middle; 
        width:19px;    height:19px;    margin:-1px 4px 0 0;
        background:url(check_radio_sheet.png) left top no-repeat;
    }
    input[type="checkbox"]:checked + label .fakeCheckbox {
        background:url(check_radio_sheet.png) -19px top no-repeat;
    }

The idea is quite similar to what we would do using javascript but instead of using a script to set the “on/off” we just use the CSS3 :checked selector to know if the radio is on/off and determine the background position of the span (fake checkbox). A nice improvement on previous method.

That said, there is a bug on iPads previous to iOs7 (I think it’s already fixed on iOs7) as they don’t seem to handle the HTML very very old standard of clicking the input when you click its label. To fix that, you only need to add an empty onclick=”” on the label which will fix that label on iPads and also allow this trick to work (have in mind you are not just adding that onclick to make this work, but also to make the labels work on iPads).

<input type="checkbox" id="c1" name="cc" />
<label for="c1" onclick=""><span class="fakeCheckbox"></span>Check Box 1</label>

Leave a Reply

Close Bitnami banner
Bitnami