TOC

The community is working on translating this tutorial into Portuguese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Advanced Selectors:

The Adjacent Sibling Selector

In the previous chapter, we discussed the sibling selector, which allows us to select all elements which follows another element within the same parent. However, using the Adjacent sibling selector, you can limit this to only include the first element which comes directly after the first element in the markup. This can be a bit difficult to imagine, so allow me to illustrate it with an example:

<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>
	<p>Even more text here</p>
	<h2>Hello, world!</h2>
	<p>Text here as well...</p>
	<p>But no more!</p>
</div>

With the adjacent sibling selector, we have just specified that the first paragraph element after all H2 elements should use italic text. If we had used the general sibling selector, like we did in the previous chapter for an example much like this one, all paragraph elements after the first H2 element would be targeted. The syntax for the adjacent sibling selector is just as easy though, as you can see - the two selector parts are simply joined by a plus character (+).

Of course you can use more than simple element selectors - the two parts of the general AND the adjacent sibling selectors can be as specific as you want them to, utilizing all the techniques we have previously looked at in the various chapters on selectors. Here's an example, just to prove my point:

<style type="text/css">
div#content h2.main + p {
	font-style: italic;
	color: Blue;
}
</style>

<div id="content">
	<h1>Hello, world!</h1>
	<p>Some text here</p>
	<h2 class="main">Hello, world!</h2>
	<p>Some text here</p>
	<p>More text here</p>
	<h2>Hello, world!</h2>
	<p>Text here as well...</p>
</div>

The selector is simply made up of two parts in this case, separated by the plus sign, and you can be as specific in each of the parts as you want to.

Summary

The general sibling selector and the adjacent sibling selector allows you to target elements based on which element comes before them, within the same parent element. As we saw in this chapter, the adjacent sibling selector is a bit more restrictive, allowing you to target only elements which comes right 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!