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/

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
lajlev
  • 772
  • 2
  • 7
  • 22
  • 5
    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. – M H Aug 26 '16 at 04:43
  • If anyone still search for a solution, this can help: https://jsfiddle.net/eduardoks98/wv0amod8/ – Eduardo Steffens Jan 18 '22 at 14:35

2 Answers2

14

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

See this post that talking about it here.

Community
  • 1
  • 1
Val
  • 762
  • 8
  • 32
  • 1
    Keep in mind that the [new draft](http://dev.w3.org/csswg/selectors4/#subject) uses `!` instead of `$` to specify the subject of the selector. – 0b10011 Jun 01 '12 at 13:59
  • 1
    This jQuery plugin claims to add the behavior to your stylesheets: http://demo.idered.pl/jQuery.cssParentSelector/ – Brilliand Jun 01 '12 at 14:17
  • I've tried out the jQuery plugin without luck, looking forward to the new CSS4 selector. – lajlev Jun 04 '12 at 08:04
  • Or you can directly use something like http://lesscss.org for example ! – Val Jun 04 '12 at 09:11
  • 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 down – Amir Surnay Nov 20 '13 at 11:36
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

Teocci
  • 7,189
  • 1
  • 50
  • 48
Ali Tenni
  • 190
  • 2
  • 11