Clean CSS checkbox image replacement

I have a list of checkboxes in a table. (one of the row CB in a row)

<tr><td><input type="checkbox" class="custom_image" value="1" id="CB1" /><label for='CB1'>&nbsp;</label></td></tr> <tr><td><input type="checkbox" class="custom_image" value="2" id="CB2" /><label for='CB2'>&nbsp;</label></td></tr> <tr><td><input type="checkbox" class="custom_image" value="3" id="CB3" /><label for='CB3'>&nbsp;</label></td></tr> <tr><td><input type="checkbox" class="custom_image" value="4" id="CB4" /><label for='CB4'>&nbsp;</label></td></tr> 

I would like to replace the checkbox image with a pair of custom on / off images, and I was wondering if someone better understood how to do this using CSS?

I found this CSS Ninja tutorial, but I have to admit it's a little complicated for me. http://www.thecssninja.com/css/custom-inputs-using-css

As far as I can tell, you are allowed to use the pseudo-class

  td:not(#foo) > input[type=checkbox] + label { background: url('/images/off.png') 0 0px no-repeat; height: 16px; padding: 0 0 0 0px; } 

My guess was that by adding the above CSS, the checkbox would at least display the image in the OFF state by default, and then I would add the following to get ON

  td:not(#foo) > input[type=checkbox]:checked + label { background: url('/images/on.png') 0 0px no-repeat; } 

Unfortunately, it seems that I missed a critical step somewhere. I tried using my own CSS3 selector syntax to match my current setup, but should be missing something (16x16 images if that matters)

http://www.w3.org/TR/css3-selectors/#checked

EDIT: I missed something in the tutorial where it applies the image change to the label, not the input itself. I still don't get the expected replacement image for the checkbox result on the page, but I think I'm closer.

+75
css checkbox css-selectors css3
Sep 22 '10 at 18:03
source share
3 answers

You are already there. Just make sure you hide the flag and associate it with the label you use with input[checkbox] + label

Full code: http://gist.github.com/592332

JSFiddle: http://jsfiddle.net/4huzr/

+119
Sep 22 '10 at 19:30
source share

Using javascript seems unnecessary if you choose CSS3.

Using the :before selector, you can do this in two lines of CSS. (no script).

Another advantage of this approach is that it does not rely on the <label> and works even without it.

Note: in browsers without CSS3 support, the checkboxes will look fine. (backward compatibility).

 input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; } input[type=checkbox]:checked:before { background:green; }​ 

Here you can see the demo: http://jsfiddle.net/hqZt6/1/

and this one with images:

http://jsfiddle.net/hqZt6/6/

+36
Aug 07 2018-12-12T00:
source share

If you are still looking for more customization,

Check out the following library: https://lokesh-coder.imtqy.com/pretty-checkbox/

thank

+3
Jul 22 '16 at 18:46
source share



All Articles