1

I have some html that looks like this:

<div id="parent">
  <div id="child"></div>
</div>

I want to apply a default background color to #parent except for when it contains a #child.

So the CSS should end up looking something like this:

#parent {
  background: red
}
#parent:contains(#child) {
  background: none
}

However, I can't get the :contains pseudo selector to work that way. Is there a way to achieve this?

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Andrew
  • 196,883
  • 184
  • 487
  • 673

2 Answers2

1

:contains() was only intended to match elements containing certain text, not elements containing certain other elements. It is because of the complications associated with matching elements by text that there were almost no browser implementations, leading to :contains() being dropped from the spec.

Since there is no parent selector in CSS, and :has() (which does look at elements) only exists in jQuery, you won't be able to achieve this with CSS yet.

For the record, jQuery implements :contains() as well, but it does so according to the old spec, so it uses the name :has() for elements instead.

Community
  • 1
  • 1
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
0

With jquery

if($("#child").length>0) $("#parent").css("backgroundColor","#fff");

Its not possible with pure css.

user1475195
  • 59
  • 1
  • 1
  • 5
  • with jQuery you can do $('#parent:has(#child)').css...but I am going for a CSS only solution. – Andrew Jul 18 '12 at 18:06