How to target the parent div from child div?

How, in CSS, can one target an element only when it is the parent of another specific element?

  • Example: <div>      <input type="checkbox"> </div> I want the div to have a different background color when the checkbox is checked, and when it is not checked. To clarify, I am looking for a selector to replace what I have written as (when) div{background: #aaa;} div (when) input:checked{background: #ccc} This is pretty straightforward with JavaScript, but how would I do this in CSS?

  • Answer:

    You can't, you have to use JS to do this.  This was actually proposed to the CSS Working Group but they rejected it on the grounds of potential infinite loop/performance issues, see Selectors are unable to ascend on wikipedia: http://en.wikipedia.org/wiki/Cascading_Style_Sheets#Limitations

Mark Vilrokx at Quora Visit the source

Was this solution helpful to you?

Other answers

There are plans on adding a parent selector in CSS4. More info can be found here: http://dev.w3.org/csswg/selectors4/ But as of now there is no way to achieve what you want only with CSS.

Dimitar Panov

Sorry i am a little late but this is very easy. You don't really need any parental selectors or whatsoever. Keep in mind... :before and :after pseudo elements are your best friends in CSS. No need for CSS4 or JS for such things.HTML <div class = "optbox"> <input class="cb" type="checkbox" name="vehicle" value="Bike"> <span class ="cbt">I have a bike</span> </div> CSS .optbox { position: relative; width: 120px; height: 20px; padding: 1em; } .cb { position: absolute; right: 25px; } .cb:checked + .cbt:after { background-color: lightgreen; } .cbt:after { content: ""; z-index: -1; position: absolute; top: 0; left: 0; height: 100%; width: 100%; border-radius: 10px; background-color: tomato; } please watch it happening at the http://codepen.io/omerillo/pen/QyGrRr/ snippet.

Ömer Kaşdarma

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.