Skip to: content, navigation

by Tommy Olsson and Paul O’Brien

General Sibling Selector (CSS selector)

Browser support full matrix
IE7+ FF1+ Saf3+ Op9.2+
Buggy Full Full Full
Spec
Version
CSS3

Example

This selector matches all p elements that are siblings to h2 elements:

h2~p {
  ⋮ declarations
}

Try it yourself!View all demos

Description

The general sibling selector is available in CSS3, and the combinator used in this selector is a tilde character (~).

The selector matches elements that are siblings of a given element. This example will match a p element if it’s a sibling of an h2 element:

h2~p {
  ⋮ declarations
}

The elements don’t have to be adjacent siblings, but they have to have the same parent, and the h2 element has to occur before the p element in the document source. Let’s apply the above selector to some more examples:

<h2>Heading</h2>
<p>The selector above matches this paragraph.</p>
<p>The selector above matches this paragraph.</p>

Here, both paragraphs match the sibling selector h2~p, because the p elements are siblings to the h2 element.

The paragraph below isn’t a sibling to the heading—they don’t have the same parent—so our selector won’t match this paragraph:

<h2>Heading</h2>
<div>
  <p>The selector above does not match this paragraph.</p>
</div>

Only the second paragraph above is matched by the sibling selector h2~p—even though they’re siblings—because the first p element occurs before the h2 element:

<p>The selector above does not match this paragraph.</p>
<h2>Heading</h2>
<p>The selector above matches this paragraph.</p>

Compatibility

IE5.5None
6.0None
7.0Buggy
Firefox1.0Full
1.5Full
2.0Full
Safari1.3None
2.0None
3.0Full
Opera9.2Full
9.5Full

In Internet Explorer 7, this selector fails if a comment appears between the combinator and the simple selector that follows it.

If one of the simple selectors is missing, Internet Explorer 7 acts as if there were a universal selector in its place, instead of failing as it should.

User-contributed notes

There are no comments yet.

Add a note

To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.

Related Products

The Principles of Beautiful Web Design

Best Seller!

You don’t need to go to Art School to design great looking web sites!

Book Cover: The Principles of Beautiful Web Design

Download the FREE sample chapters