2

I'm trying to use a custom image for checkboxes, as discussed in this question:

Pure CSS Checkbox Image replacement

My checkboxes appear in a grid, so don't need a label associated with them. However, I find that if the label isn't present, the technique discussed in that question doesn't work.

For example, here's the relevant css:

input[type=checkbox] {
    opacity: 0;
}

input[type=checkbox]  {
    height: 17px;
    width: 17px;
    background: url('/resources/img/checkBox-unchecked.png') 0 0px no-repeat;
}

input[type=checkbox]:checked {
    background: url('/resources/img/checkBox-checked.png') 0 0px no-repeat;
    height: 17px;
    width: 17px;
    padding: 0 0 0 0px;
}

Declaring just a simple input doesn't render the image:

<input type="checkbox">

However, if I modify the css, appending the + label, and append a label to the markup, as discussed in the solution, it works:

input[type=checkbox] {
    opacity: 0;
}

input[type=checkbox] + label {
    height: 17px;
    width: 17px;
    background: url('/resources/img/checkBox-unchecked.png') 0 0px no-repeat;
}

input[type=checkbox]:checked + label  {
    background: url('/resources/img/checkBox-checked.png') 0 0px no-repeat;
    height: 17px;
    width: 17px;
    padding: 0 0 0 0px;
}

<input type="checkbox"><label></label>

This renders as expected.

Why does the first solution not work?

How can I acheive this without having to add labels that aren't required?

Community
  • 1
  • 1
Marty Pitt
  • 28,822
  • 36
  • 122
  • 195

2 Answers2

3

You left the following in your first example:

input[type=checkbox] {
    opacity: 0;
}

That will make it "not render."

Now, having removed that trifling little style, you'll likely ask

Okay, the control shows up now... so, why doesn't the background image show up?

That's because you don't have any real control over how radio-buttons, check-boxes, combo-boxes, file-upload controls, etc are styled. The label solution works because you can happily style a label to the full extent of css. The controls I've mentioned? Not so much...

canon
  • 40,609
  • 10
  • 73
  • 97
  • Thanks! What the other question/answer didn't make clear (that you have) is that the solution doesn't style the checkbox, it styles the label. The checkbox is hidden. It's all just smoke'n'mirrors. – Marty Pitt Jun 01 '12 at 23:30
0

I'm no expert but, if you set all input checkbox to 0 opacity, won't if effectively hide the whole checkbox? Maybe try the method mentioned in this post : http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

JudeJitsu
  • 730
  • 1
  • 10
  • 17
  • 2
    That solution uses javascript and still injects extra dom nodes... which is what the OP is trying to avoid. – canon Jun 01 '12 at 03:07