tags:

views:

1063

answers:

2

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.

+1  A: 
input[type="radio"]:checked+label{ font-weight: bold; } 
 //a label that is immediately preceded by 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

Stephen
A: 

You could use a bit of jQuery:

$('input:radio').click(function(){
    $('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});

You'd need to make sure your checked radio buttons have the correct class on page load as well.

meanstreakuk
Yes... it is of course possible to do this via javascript (frameworks), but it is not as simple as it seems. What happens if something else has already checked the box? What script will remove this class if another radio in the same group is selected? It gets too complicated really quick. I want to use the browser's built in form+css functionality because it will work every time.
Stephen
Yeah sorry - I really should read questions better! I'll learn...
meanstreakuk