views:

167

answers:

4

Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?

I think this is best explained using an example.

Note: I'm trying to style the parent element, depending on what child elements it contains.

/* note this is invalid syntax. I'm using the non-existing
   ":containing" pseudo-class to show what I want to achieve. */

<style>
  div:containing div.a { border: solid 3px red; }
  div:containing div.b { border: solid 3px blue; }
</style>

<!-- the following div should have a red border because
     if contains a div with class="a" -->
<div>
  <div class="a"></div>
</div>

<!-- the following div should have a blue border -->
<div>
  <div class="b"></div>
</div>

Note 2: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.

A: 

Just use the > symbol.

For example

div > div.a { border: solid 3px red; }

Take a look at this cheat sheet it will assist you in creating the correct selectors.

http://www.addedbytes.com/download/css-cheat-sheet-v2/png/

Laykes
I don't think that's what he's asking... he's asking how to style the _parent div_, not a child OF that div.
Seth Petry-Johnson
I misunerstood. I shall delete my answer.
Laykes
A: 

Withdrawn because I misunderstood the question.

Robusto
I don't think that's what he's asking... he's asking how to style the _parent div_, not a child OF that div.
Seth Petry-Johnson
Yeah, that's why I edited the question to say I don't have a clue. :)
Robusto
+3  A: 

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. It's selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a css class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with css class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for jQuery "has" selector.

KP
Awesome post, thanks!
Charlie Somerville
+2  A: 

Basically, no. The following would be what you were after in theory

div.a < div { border: solid 3px red; }

Unfortunately it doesn;t exist.

There are a few write ups along the lines of "why the hell not", a well fleshed out one by Shaun Inman is pretty good.

http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors

Justin Wignall