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?
The checkbox is an HTML element used to take input from the user. It is hard to style the checkbox, but pseudo-elements makes it easier to style a checkbox. This HTML element is generally used on every website, but without styling them, they look similar on every website.
The :checked selector matches every checked <input> element (only for radio buttons and checkboxes) and <option> element.
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;
}
Live demo
The +
is a sibling selector. It is not supported by IE8 and below.
Sorry, see:
Is there a CSS parent selector? and Complex CSS selector for parent of active child
for more discussion about this topic, but it doesn't seem to be possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With