简体   繁体   中英

Target all p elements that follow an h2 with CSS

How can I target all p elements that follow a heading eg...

<h2 class = 'history'>History</h2>
<p>this is paragraph 1</p>
<p>this is paragraph 2</p>
<p>this is paragraph 3</p>

<h2 class = 'present'>Present</h2>
<p>I don't want to target this paragraph</p>
<p>I don't want to target this paragraph</p>
<p>I don't want to target this paragraph</p>

by using .history + p I can target paragraph 1, but how to target the other paragraphs until I get to the 'Present' H2 tag?

If there aren't any other p elements, you can use ~ instead of + :

.history ~ p

If there are any more p elements that come after your second h2 , and you only want to select those between h2.history and h2.present , I don't think it's possible with current CSS selectors. The general sibling selector ~ matches every p sibling that comes after your h2 , regardless of whether there are any other siblings among them.

That said, you can easily accomplish it using jQuery:

$('.history').nextUntil('.present')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM