mk_89
mk_89

Reputation: 2742

If input is checked set parent background

My html markup looks like this..

<div class="siteCheckboxes">
   <label for="filterAll">
      All <input name="filterAll" type="checkbox" id="filterAll" checked="checked"  />
   </label>
</div>

I need to know how to change the color of the parent label the checkbox is in. I have tried doing...

input[type="checkbox"]:checked > label{ background-color:#F00; } 

in order to change the parent labels background colour, but this does not work. What is the correct way to do this?

Upvotes: 1

Views: 4912

Answers (3)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201896

You can do this in pure CSS if you use markup where the input and label elements are adjacent siblings and not nested and the label appears after the checkbox (which is much more common usage and hence better usability):

<input name="filterAll" id="filterall" type="checkbox" id="filterAll" 
       checked="checked"  />
<label for="filterAll">All</label>

Then you can use the adjacent sibling selector +:

input[type="checkbox"]:checked + label { background-color:#F00; } 

Upvotes: 1

TheZ
TheZ

Reputation: 3732

CSS cannot modify parents based on children. It is a one way path of parent -> child access.

-EDIT:

As Little Big Bot points out in the comments, there are sibling selectors (+ and ~) available but they are not fully supported yet. And they would not help you if you are nesting the elements as you state. In any case here they are:

http://reference.sitepoint.com/css/adjacentsiblingselector

http://reference.sitepoint.com/css/generalsiblingselector

Upvotes: 3

Ayman Safadi
Ayman Safadi

Reputation: 11552

This cannot be done with strictly CSS. CSS (not even CSS 3) does not have a "parent" selector.

More info: http://css-tricks.com/parent-selectors-in-css/

Upvotes: 2

Related Questions