Friday 30 December 2011

CSS: adjacent sibling selectors

   


Who knows what adjacent sibling selectors are? Hmmm... it looks like not many of us are aware of their existence... It is quite true that considering all possible CSS selectors, adjacent sibling selectors are the most unknown and rarely used even by expert web developers. Why? Don't know... Nevertheless they are quite useful and efficient in applying CSS rules to specific elements.

I will show you an example and we will explore adjacent sibling selectors use.

What are adjacent sibling selectors?
We can define adjacent sibling selectors as stated by the W3C site:
"Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments)." (quote from W3C)

It is quite simple to understand how such selectors can became handy.
A possible use is related to image captions. Let's say we use images all over our page and, at the same time, we have different div elements which contain image caption or other text. If we want to apply a CSS rule just to image captions, we can benefit from the adjacent sibling selector, because we will style only <div> tags that are preceded by <img> tags. Something like:
img + div {
   color: #FF0000;
}
With the above rule, all the image captions will have a red text.

A live example
We are going to style specific adjacent tags. We are going to have two headings (note: I am using <h5> heading tags because of the blogger platform; if I use <h1> all the page will be with red text!). The first is followed by a span element, while the second is followed by a div element. We want to make the text inside the div in red.

First heading
This is a span

Second heading
This is a div
Let's see the code behind that.
First of all the CSS rule:
<style type="text/css">
h5+div {
  color: #FF0000;
}
</style>
And then the HTML:
<h5>First heading</h5>
<span>This is a span</span>
<br><br>
<h5>Second heading</h5>
<div>This is a div</div>
Very simple isn't it?

Now tell me you did know about it.
Share your experience, please, using the comments section below.

1 comment:

  1. Thanks for this! Awesome how-to.

    I especially love how this can be combined with :not()

    For example:

    #secondary_navigation:not(.skinned) + .instance-heading:not(.skinned) {
    margin-top: -20px;
    border-radius: 0px;
    }

    ...which I have a sneaky suspicion can be optimized.

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.