TOC
Advanced Selectors:

The Sibling Selector

We just looked at how the child and descendant selectors can be used to target specific children/grandchildren of an element, but what if you want to target siblings instead? CSS has a couple of selector types for that as well, and in this chapter, we'll check out the general sibling selector.

With the general sibling CSS selector, which takes a selector, followed by a tilde character (~) and then the selector you wish to target, you can target elements by requiring the presence of another element within the same parent element. Another requirement is that the first part of the selector needs to be present in the markup BEFORE the targeted element, even though they are all children of the same parent. Here's an example which will demonstrate it:

<style type="text/css">
h2 ~ p {
	font-style: italic;
}
</style>

<div id="content">
	<h1>Hello, world!</h1>
	<p>Some text here</p>
	<h2>Hello, world!</h2>
	<p>Some text here</p>
	<p>More text here</p>
</div>

So, all of the text elements are children of the same div element. We then specify that paragraph elements which are siblings to an H2 element should be in the italic style. As you can see, if you try the example, this means that the last two paragraph tags will be in italic, but not the first, because it comes before the H2 element in the markup. You will also notice that the sibling selector does not affect grandchildren:

<style type="text/css">
h2 ~ p {
	font-style: italic;
}
</style>

<div id="content">
	<h1>Hello, world!</h1>
	<p>Some text here</p>
	<h2>Hello, world!</h2>
	<p>Some text here</p>
	<div>
		<p>More text here</p>
	</div>
</div>

Notice how the paragraph inside the second div tag is no longer affected because it's no longer directly related to the H2 element.

Summary

The general sibling selector allows you to target elements based on other elements within the same parent/child scope. However, you will notice that this can be a very broad set of elements, depending on how many elements the parent holds. Using the Adjacent sibling selector, which we'll discuss in the next chapter, you can limit the elements to those immediately after another element.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!