<label> style based on <input> state

Is it possible, using only CSS, the style of the HTML shortcut, depending on its input state?

In my case, I want the <input type="checkbox"> style to be based on validation.

I tried putting a shortcut in the input, but Firefox and Chrome (at least) seem to parse them as siblings, although they are clearly nested in the original source. And I don’t know how to write a CSS rule that can be indirect through the for = attribute.

Do I need to hack Javascript on this?

+7
html input css checkbox
source share
2 answers

They do not need to be nested, which is used for the "for" attribute in the <label> element.

In modern browsers (supporting CSS 2.1) you can use the sibling selector, for example

 input + label { /* rules */ } 

You will need to have markup in a strict marriage relationship, for example:

 <input name="cb" id="cb" type="checkbox"><label for="cb">Checkbox</label> 
+5
source share

Using an adjacent / selector selector plus an attribute selector will make it work:

 <form> <style> INPUT[checked=checked] + LABEL { color: #f00; } </style> <div> <input type="checkbox" id="chk1" /> <label for="chk1">Label #1</label> </div> <div> <input type="checkbox" id="chk2" checked="checked" /> <label for="chk2">Label #2</label> </div> </form> 
+4
source share

All Articles