CSS selector for a checked radio button's label

Stephen picture Stephen · Sep 16, 2009 · Viewed 374.8k times · Source

Is it possible to apply a css(3) style to a label of a checked radio button?

I have the following markup:

<input type="radio" id="rad" name="radio"/>
<label for="rad">A Label</label>

What I was hoping is that

label:checked { font-weight: bold; }

would do something, but alas it does not (as I expected).

Is there a selector that can achieve this sort of functionality? You may surround with divs etc if that helps, but the best solution would be one that uses the label ''for'' attribute.

It should be noted that I am able to specify browsers for my application, so best of class css3 etc please.

Answer

Stephen picture Stephen · Sep 16, 2009

try the + symbol: It is Adjacent sibling combinator. It combines two sequences of simple selectors having the same parent and the second one must come IMMEDIATELY after the first.

As such:

input[type="radio"]:checked+label{ font-weight: bold; } 
 //a label that immediately follows an input of type radio that is checked 

works very nicely for the following markup:

<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>

... and it will work for any structure, with or without divs etc as long as the label follows the radio input.

Example:

input[type="radio"]:checked+label { font-weight: bold; }
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>