15

Possible Duplicate:
Complex CSS selector for parent of active child
Is there a CSS parent selector?

Is there a way to design parent class based on if its child elements has a specific class?

<div class="container">
   <div class="content1">
      text
   </div>
</div>

.

<div class="container">
   <div class="content2">
      text
   </div>
</div>

I want to design the first .container differently based on if the child class is content1 or content2. It must be pure css solution, without javascript.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
Alvarez
  • 1,303
  • 1
  • 10
  • 28

3 Answers3

10

2012 answer:

No, you can't do that. CSS can't select elements based on their children, except to check whether or not the element is empty.

2022 answer: the :has() selector, see https://developer.mozilla.org/en-US/docs/Web/CSS/:has

e.g. .container:has(> .content1) will select elements classed as .container which are the direct parent of an element classed as .content1.

tuff
  • 4,895
  • 6
  • 26
  • 43
5

What you're asking for is the the mythical CSS parent selector. Perhaps some day.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
5

Why not use container1 + content and container2 + content?

<div class="container1">
    <div class="content">
      text
    </div>
</div>

<div class="container2">
    <div class="content">
        text
    </div>
</div>

And then write CSS like so:

.container1 .content {
    /* Container 1 styles here */
}

.container2 .content {
    /* Container 2 styles here */
}
Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
  • Won't those apply the styles to the .content elements? Just to clarify, I thought his requirement was to apply styles to the container elements and not the children. – Asad Saeeduddin Oct 16 '12 at 19:02
  • @Asad: Yes, if there is other content outside of the `.content` div, but inside a `.container` div that needs to be styled, then the OP can simply write rules for `.container1` and `.container2` – Kevin Boucher Oct 16 '12 at 19:04