Change parent div on input[type=checkbox]:checked with css [duplicate]
Asked Answered
R

2

29

I can figure out how to make the parent div change when checkbox is checked :( Changing the following paragraph works fine.

Tried this approach without luck in Chrome:

HTML

​<div>
    <input type="checkbox​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​" checked>
    <p>Test</p>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS

div {
    background: pink;
    width: 50px;
    height:50px;
}
div + input[type=checkbox]:checked {
  background: green;
}

input[type=checkbox]:checked + p {
    background: blue;
}

http://jsfiddle.net/lajlev/3xUac/

Rhu answered 1/6, 2012 at 7:25 Comment(2)
I hate when people mark as duplicate what the question they use and the duplicate doesn't even have an answer or publicly voted up answer.Beriosova
If anyone still search for a solution, this can help: jsfiddle.net/eduardoks98/wv0amod8Stricture
M
15

No way to select a parent with CSS only (until CSS4), so you must use JS..

See this post that talking about it here.

Misprize answered 1/6, 2012 at 7:42 Comment(5)
Keep in mind that the new draft uses ! instead of $ to specify the subject of the selector.Goggin
This jQuery plugin claims to add the behavior to your stylesheets: demo.idered.pl/jQuery.cssParentSelectorWhitewash
I've tried out the jQuery plugin without luck, looking forward to the new CSS4 selector.Rhu
Or you can directly use something like lesscss.org for example !Misprize
i don't think it'll be in CSS4. because it CSS is have cascade style, which means you can climb up, you can just go downFrenzied
J
8

You cannot access the parent but if you reorganize your html code and make the input and div elements siblings then you can try this:

div {
  background: pink;
  width: 50px;
  height: 50px;
}

div p {
  color: black;
}

input[type=checkbox]:checked+div {
  background: green;
}

input[type=checkbox]:checked+div p {
  background: blue;
  color: white;
}
<input type="checkbox" checked>
<div>
  <p>Test</p>
</div>

external link

Joyejoyful answered 4/3, 2015 at 11:21 Comment(2)
<div> <p>Test</p> </div><input type="checkbox" checked> // is this possible ?Ventage
@hanu not really, the + defines the next element, there is nothing to access the previous sibling.Rodriguez

© 2022 - 2024 — McMap. All rights reserved.