Child and sibling selectors

I was trying to style a bit of html without having to add a new class into the markup and came across two types of CSS selectors that I haven’t used before called child and sibling selectors.

You can use child selectors to target the direct children of an element. The syntax is parent > child. Here’s an example that turns any p tags directly inside an “outerdiv” div blue:

  1. div.outerdiv > p
  2. {
  3.  background-color: lightblue;
  4. }

child selectors

You can use sibling selectors to target elements that are next to each other. The syntax is element + sibling. Here’s an example that will make any paragraph tag that’s next to another paragraph tag yellow:

  1. p + p
  2. {
  3.  background-color: yellow;
  4. }

sibling selectors

You can see a more complete example in action.

The cool thing is that between these two tags you could actually walk the entire document tree and target any of the children that you wanted without having to explicitly give them a name. I can see this being really useful in situations where you want to apply a css skin but you have no control over the markup.

The not-so-cool thing is that they currently will work in Firefox (haven’t tested anything else) but not IE7. Hurry up IE team and give us more selectors (and multiple background images for a single element)!

Posted on 20 Jan 07 by Helen Emerson (last updated on 20 Jan 07).
Filed under CSS