Let's say I have a basic webpage:
<LABEL ID="THE_LABEL" FOR="THE_CHECKBOX"><INPUT TYPE=checkbox ID="THE_CHECKBOX"/> Blue when checked!</LABEL>
Now let's say that I want the label text to be red when it's unchecked and blue when it's checked. How would I do this? I want something as basic as the following. Here, I use a hypothetical operator "<
", which would mean "has the child", but of course it won't work, as there's no such operator:
#THE_LABEL{
color:red;
}
#THE_LABEL < #THE_CHECKBOX[checked]{
color:blue;
}
Everything but the theoretical "<
" is valid CSS, which makes me wonder if there's a real way to achieve this behavior. Does anyone know of a valid CSS 3 (or lower version) way to style a label based on the state of its checkbox, without using JavaScript?
You shouldn't be putting the input field within the label.
Since the contents of the label appear after the checkbox, just make your HTML this way:
<INPUT TYPE=checkbox ID="THE_CHECKBOX"/>
<LABEL ID="THE_LABEL" FOR="THE_CHECKBOX">Blue when checked!</LABEL>
And then use this CSS:
#THE_LABEL {
color: red;
}
#THE_CHECKBOX:checked + #THE_LABEL {
color: blue;
}
The +
is a sibling selector. It is not supported by IE8 and below.