About the indirect adjacent combinator (~) in CSS

Similar to the CSS Adjacent Sibling Combinator that I wrote about before, the indirect adjacent combinator is pretty nifty and supported by IE7+, FF2+, Opera 9.5+, Safari 3+, and even Konqueror. It is actually part of the CSS3 spec but it’s surprisingly well supported. Here’s how to use it and what it does:

Using the CSS Indirect Adjacent Combinator

h3 ~ p {
  color: #FFFFFF;
  padding-left: 20px;
  border-left: 3px solid;
}

CSS Indirect Adjacent CombinatorThis would affect each <p> element that is a sibling of a preceding <h3> element. This is different from the Adjacent Sibling Combinator (+) in that it affects all following <p> siblings instead of just the immediate sibling. Let us see an example:

CSS Indirect Adjacent example

Example 1: Adjacent Sibling combinator (h4 + p) test:

Heading 4

Paragraph 1 – This should be gray and red

Paragraph 2 – This should NOT be red

Example 2: Indirect Adjacent Sibling combinator (h4 ~ p) test:

Heading 4

Paragraph 1 – This should be gray and red

Paragraph 2 – This should also be gray and red!!

Here is the CSS for the above example:

#indirect-example1 h4 + p,
#indirect-example2 h4 ~ p {
    background-color: #CCC; color: #F00;
}

Cool, right? So you see how you can use this instead of the (+) selector to apply styles to the elements you want in basically everything except IE6-! This is a good example of something used for progressive enhancement that should be used to add detail to elements to give your users more information.

Update: Sorry for the name confusion. The latest draft of the CSS3 spec calls this the "General Sibling Combinator" and I didn’t think it had changed from "Indirect Adjacent Combinator" when I first learned of it so I used the latter. My apologies!

Have you ever used this? What was your experience and what ideas do you have for this CSS gem?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Simple HTML is allowed. Use those <code> tags!

{Responses: 23}