Select Label by Input type

2019-04-26 15:48发布

问题:

Is there a way to exclude or select Label by input types, something similar to input field?

label:not([type=checkbox])
label[type=checkbox] 

回答1:

If you give your checkboxes specific id's that all start with the same thing, you could do the following:

HTML

<input type="checkbox" id="chkTerms" />
<label for="chkTerms">Read terms & conditions</label>

CSS

label[for*="chk"], label[htmlfor*="chk"]
{
css here
}

Probably modern browsers only though. EDIT: I have just tried a fiddle: link and it works in chrome and IE 8 & 9 but not 7. I did not try it in FF.

EDIT2: Just to give an explanation of what is going on here, the square brackets looks for an attribute called for. The the asterix changes the behaviour of the equals from just a plain equals, to mean contains - wherever the for attribute contains "chk" it will apply that style. You can replace the * with a ^ and it will change it to mean starts with instead of contains.

EDIT3: BoltClock has provided a fix for IE7 in a comment, I have updated the answer to include it.



回答2:

How about input[type=checkbox] + label { /*label style here*/ } ? It might work if text is just after the input element. I have not tested that.



回答3:

You can use your checkbox with basic data-attribute reference..

<input type="checkbox" name="checkbox-1" id="checkbox-0" class="custom" />
<label for="checkbox-0">Whatever</label>

If you not expect this... let us know...