9

What does the + in this CSS rule mean?

h2 + p { 
  font-size: 1.4em; 
  font-weight: bold;
  color: #777; 
} 
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356

4 Answers4

30

+ is the adjacent sibling combinator.

That means the selector h2 + p only selects the p that comes immediately after an h2.

An illustration:

<h2>Headline!</h2>
<p>The first paragraph.</p>  <!-- Selected [1] -->
<p>The second paragraph.</p> <!-- Not selected [2] -->

<h2>Another headline!</h2>
<blockquote>
    <p>A quotation.</p>      <!-- Not selected [3] -->
</blockquote>

What's selected and what's not:

  1. Selected
    This p comes right after the first h2.

  2. Not selected
    This p occurs after the first p as opposed to the h2. Since it doesn't immediately follow the h2, it's not selected.

    However, since it still follows the h2 element, just not immediately, the selector h2 + p won't match this element, but h2 ~ p will, using the general sibling combinator instead.

  3. Not selected
    This p is located within a blockquote, and there's no h2 before it inside the quote to satisfy its selector.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
4

It selects all p elements that are directly after a h2 element in the DOM. Thus, the following p element would be styled:

<h2>A heading</h2>
<p>This paragraph will be styled.</p>

But this wouldn't:

<h2>A heading</h2>
<hr>
<p>This paragraph will NOT be styled.</p>

And neither would this:

<p>This paragraph will NOT be styled.</p>
<h2>A heading</h2>

...or this:

<h2>A heading</h2>
<section>
    <p>This paragraph will NOT be styled.</p>
</section>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
You
  • 22,800
  • 3
  • 51
  • 64
2

it selects all P tags that are directly beside an h2 tag. Then gives it the said attributes.

dockeryZ
  • 3,981
  • 1
  • 20
  • 28
  • 2
    Directly *after*, even. And CSS applies to elements, not tags. – You Aug 01 '10 at 12:57
  • 2
    This answer is ambiguous. It will select one P element (not all) that comes directly after a H2 element. – ase Aug 01 '10 at 12:59
0

Only affects first p which is directly following (comes directly after) the H2

example 1:

<h2></h2>
<p></p> <!-- THIS ONE IS AFFECTED -->
<p></p> <!-- THIS ONE IS NOT AFFECTED -->
<p></p> <!-- NOR THIS ONE -->
<p></p> <!-- NOR THIS ONE -->
<p></p> <!-- ETC -->

example 2:

<h2></h2>
<div></div>
<p></p> <!-- THIS ONE IS NOT AFFECTED -->