Markeee
Markeee

Reputation: 573

Select all <h2> that follow a <p> tag

Is there a way to select all headings (in my example <h2>) that follow the <p> tag?

For example, is it possible for me to select the second and third h2, so that I can put some padding-top?

<main>
  <h2>Sub heading 1</h2>
  <p>Body text</p>
  <p>More body text</p>
  <h2>Sub heading 2</h2>
  <p>Body text</p>
  <h2>Sub heading 3</h2>
  <p>Body text</p>
</main>

Or to turn it around, select the <p> tag that comes before a <h2>? To put some padding-bottom?

Thank you

Upvotes: 0

Views: 1621

Answers (4)

Carl Edwards
Carl Edwards

Reputation: 14454

Well, if you're trying to select the second and third h2 use the general sibling (or adjacent) selector followed by nth-of-type:

p ~ h2:nth-of-type(n+2):nth-of-type(-n+3) {
  padding-bottom: 12px;
}
<main>
  <h2>Sub heading 1</h2>
  <p>Body text</p>
  <p>More body text</p>
  <h2>Sub heading 2</h2>
  <p>Body text</p>
  <h2>Sub heading 3</h2>
  <p>Body text</p>
</main>

Upvotes: 0

Intervalia
Intervalia

Reputation: 10965

Use one of the CSS Sibling selectors:

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

p + h2

The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element.

p ~ h2

UPDATE: I just re-read your question. Currently there is no way to get at a previous sibling or a parent through CSS selectors. But I have hear rumor that those are coming.

Upvotes: 1

behdad
behdad

Reputation: 54

You can do like this. It selects the next element that comes after h2 and if its an element p its going to add some padding-top to it.

h2 + p {
  padding-top: 5px
}

Upvotes: 0

Scath
Scath

Reputation: 3824

This just turns it yellow but you can style it however you want.

p + h2 { 
    background-color: yellow;
}
<h2>Sub heading 1</h2>
  <p>Body text</p>
  <p>More body text</p>
  <h2>Sub heading 2</h2>
  <p>Body text</p>

Upvotes: 1

Related Questions