Web Foundations

Adjacent Sibling Selector (CSS Selector)

By Adam Roberts

A selector that uses the adjacent sibling combinator uses the plus symbol (+), and is almost the same as the general sibling selector. The difference is that the targeted element must be an immediate sibling, not just a general sibling. Let’s see what the CSS code for this looks like:

p + p {
   text-indent: 1.5em;
   margin-bottom: 0;

This example will apply the specified styles only to paragraph elements that immediately follow other paragraph elements. This means the first paragraph element on a page would not receive these styles. Also, if another element appeared between two paragraphs, the second paragraph of the two wouldn’t have the styles applied.

So, if we apply this selector to the following HTML:

<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>

<div class="box">
  <p>Paragraph example.</p>
  <p>Paragraph example.</p>

…the styles will apply only to the second, third, and fifth paragraphs in this section of HTML.

No Reader comments