Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply styles to a label whose checkbox is checked using only CSS?

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?

like image 288
Ky. Avatar asked Aug 21 '12 05:08

Ky.


People also ask

How do I style a checkbox in CSS?

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.

Which CSS selector selects only checkboxes that are checked?

The :checked selector matches every checked <input> element (only for radio buttons and checkboxes) and <option> element.


2 Answers

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.

like image 78
xbonez Avatar answered Oct 26 '22 23:10

xbonez


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.

like image 27
Ariel Avatar answered Oct 27 '22 00:10

Ariel