【问题标题】:Target all p elements that follow an h2 with CSS使用 CSS 定位 h2 之后的所有 p 元素
【发布时间】:2011-10-03 01:17:48
【问题描述】:

如何定位标题后面的所有 p 元素,例如....

<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>

通过使用 .history + p 我可以定位第 1 段,但如何定位其他段落直到我到达“当前”H2 标记?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    如果没有任何其他p 元素,您可以使用~ 代替+

    .history ~ p
    

    如果在第二个h2 之后还有更多p 元素,并且您只想选择h2.historyh2.present 之间的元素,我认为当前的CSS 选择器不可能。通用兄弟选择器 ~ 匹配 h2 之后的每个 p 兄弟,无论其中是否有任何其他兄弟。

    也就是说,您可以使用 jQuery 轻松完成它:

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

    【讨论】:

    • 非常感谢博尔特,理想情况下我不想针对后续段落,我已经更新了我的问题以反映这一点。不过,您的 jQuery 建议会很好用。由于它只是样式,因此它不一定是 CSS 解决方案,尽管如果可能的话当然是首选。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2020-12-13
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    相关资源
    最近更新 更多