Advanced CSS: Adjacent Sibling Selectors

In my web articles thus far, when I’ve talked about CSS it’s been in terms of the basics: the box model,relative positioningpage flow, etc. In the Advanced CSS articles, I’ll be talking about aspects the you wouldn’t normally find on every page. This isn’t necessarily new stuff from CSS3, just things that you wouldn’t normally need to know to do CSS design, but can come in handy sometimes.

Generally with CSS, we select an element based on its class or ID and on its ancestors. However, sometimes we need to be a little more specific. For example, suppose that every paragraph in each section, starting with the third paragraph, should have special formatting. (Why that might be, I don’t know…but CSS is very flexible!) The adjacent sibling selector will let us do this! We simply write:

p + p + p {

rules go here

}

This says that the style only applies to paragraphs which have two preceding siblings, where a sibling is another child of the same parent.

This example was a little contrived; how about another one? Suppose that we have a page with a number of h2 and h3 headers, and we want the first h3 header in each section to have special formatting. We can’t use the :first-child psuedo-class because the h3 we want is not actually a child of any h2; it simply appears immediately after it. As such, we’ll use the following code:

h2 + h3 {

font-color: #6CFF0A;

}

Now every h3 tag which immediately follows an h2 tag is bright green, as desired.

Note: the adjacent sibling selector does not work…wait for it…in IE6 and below.