1

I'm wondering if there is a CSS selector to select any label which refers to an input type checkbox.

<label for="checkbox_1">First checkbox</label>
<input type="checkbox" name="checkbox_1" value="1">

so what works easily:

label[for='checkbox_1'] { /* styles */ }

but then I have to repeat this for every label which refers to a checkbox. I would like to do something like:

label[type='checkbox'] { /* styles */ }

Any thoughts?

supersize
  • 13,764
  • 18
  • 74
  • 133
  • In CSS4 this probably will be natively possible with `label:has([type=checkbox])`. Can’t wait for that. – Sebastian Simon Apr 23 '15 at 20:01
  • Oh wait, if they are not nested, this can be done by the `+` selector: `[type=checkbox] + label`. But this only works if `label` and `input` are the other way round… – Sebastian Simon Apr 23 '15 at 20:10
  • Okay I did some more research: [in this question](http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector) the comments suggest a future syntax like `label:has(+ [type='checkbox'])`. But [this JSFiddle](http://jsfiddle.net/bbnnt7w3/) demonstrates the use when they are the other way round. – Sebastian Simon Apr 23 '15 at 20:20
  • @Xufox thanks for your research. So basically my markup is, that label and input are seperated a wrapper div. Like: `
    `
    – supersize Apr 23 '15 at 20:32

2 Answers2

0

You can use the selector that selects all LABELS with the type attribute starting with the word "checkbox":

label[type^='checkbox']

More information about attribute selectors here: http://www.w3.org/TR/css3-selectors/#attribute-substrings

Adam Dunn
  • 132
  • 6
0

This is currently not possible with pure CSS, as far as I know. You do have a couple of options for workarounds, though:

The [attribute^='value'] selector
This will work if your labels actually start with the same identifier/word when associated with checkboxes, similarly to the code example you provided.

Example:

HTML

<label for='chckbx'>Foobar</label>
<input type='checkbox' name='chckbx_1' value='1' />

CSS

label[for^='chckbx']{/* styles */}

Writing your HTML in a certain way
This will work if you already have your <label>s and their associated <input />s in their own container, or if you can modify your HTML to be that way. The trick is to select the checkbox element's container via CSS, and then style it's child <label>s.

Example:

HTML

<div class='checkboxContainer'>
    <label for='foo'>Foobar</label>
    <input type='checkbox' name='foo' value='1' />
</div>

CSS

.checkboxContainer > label{/* styles */} 

Using JS
I can write a simple code example to do this with JavaScript(/jQuery), if you want me to.

user4780006
  • 107
  • 1
  • 4