views:

31

answers:

3

Every time I hover over the label of a checkbox it turns yellow:

Markup

<input type="checkbox" value="hello" id="hello" name="deletefiles[]"/>
<label for="hello">hello</label>

CSS

label:hover, label:active {
   background:yellow;
}

When I hover over the related checkbox, I want the label to highlight. Is there a way to fire the same hover rule using CSS if I hover over the checkbox as well? Or will I have to use JavaScript for this...?

+1  A: 

You can use a CSS sibling selector, like this:

label:hover, label:active, input:hover+label, input:active+label {
    background:yellow;
}

Note that this won't work in IE6.

SLaks
Won't it be nice when IE6 market share is small enough we can stop worrying about what doesn't work in it? It's down to 7.2%. See http://www.w3schools.com/browsers/browsers_stats.asp
kbrimington
i stoped supporting ie6 5years ago! :)
second-question!!! is it possible to highlight the label IF THE CHECKBOX IS CLICKED/SELECTED? that would be interesting!
@mathiregister: I'm jealous...
SLaks
You mean if it's checked, but not if it's unchecked? You can't do that without Javascript
SLaks
do you know the js solution?
Handle the `change` event, call `val()`, and add or remove the class as appropiate (`$(this).addClass('...')`)
SLaks
@mathiregister: actually, [you could use the :checked pseudo-class](http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/html/full/flat/css3-modsel-25.html) just as you're already using :hover and :active... except that it won't work in any currently-released version of IE...
Shog9
+1  A: 

Just put the checkbox inside the label:

<label for="hello">
  <input type="checkbox" value="hello" id="hello" name="deletefiles[]"/>
  hello
</label>

Now when you hover over the checkbox, you'll also be hovering over the label, and your existing rules will suffice to highlight it.

Shog9
this is valid? interesting
WalterJ89
@WalterJ89: indeed it is... In fact, you can skip the `for` attribute on the label when the associated input is nested within!
Shog9
very cool.. Hard to believe I've never seen that or even tried it..
WalterJ89
+1  A: 

The jQuery solution:

$(document).ready(function(){
   $('#hello, label[for="hello"]').hover(function(){$(this).addClass('.hover');},
                                         function(){$(this).removeClass('.hover');});

});

...

.hover
{
   background-color: yellow;
}

And this DOES work in IE6.

Stefan Kendall