31

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/

2
  • 6
    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. Commented Aug 26, 2016 at 4:43
  • If anyone still search for a solution, this can help: jsfiddle.net/eduardoks98/wv0amod8 Commented Jan 18, 2022 at 14:35

2 Answers 2

16

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

See this post that talking about it here.

Sign up to request clarification or add additional context in comments.

5 Comments

Keep in mind that the new draft uses ! instead of $ to specify the subject of the selector.
This jQuery plugin claims to add the behavior to your stylesheets: demo.idered.pl/jQuery.cssParentSelector
I've tried out the jQuery plugin without luck, looking forward to the new CSS4 selector.
Or you can directly use something like lesscss.org for example !
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
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

2 Comments

<div> <p>Test</p> </div><input type="checkbox" checked> // is this possible ?
@hanu not really, the + defines the next element, there is nothing to access the previous sibling.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.