在css中出现h2元素之后如何设置每个奇数p元素的样式?

Tom*_*ski 5 html css css3

我有一个混乱的HTML,我无法改变它,它看起来像这样:

<div>
  <h2>This is a title cat</h2>
  <p>This is a message</p>
  <p>One cat</p>
  <p>Two cat</p>
  <p>Three cat</p>
  <h2>This is a title dog</h2>
  <p>Dog 0</p>
  <p>Dog 1</p>
  <p>Dog 2</p>
  <p>Dog 3</p>
</div>
Run Code Online (Sandbox Code Playgroud)

现在我想在h2元素更大胆之后做出每一个奇怪的p.所以我希望这是大胆的:

This is a message

Two cat

Dog 0

Dog 2
Run Code Online (Sandbox Code Playgroud)

如何在CSS中编写选择器(没有jQuery,没有JS可用)来使这些文本变粗?

Chr*_*ris 9

您可以使用css ~选择器,然后使用nth-of-type(或者nth-child)选择器来完成此操作.您可以在MDN上阅读有关这些选择器的更多信息:General Sibling Selector:nth-​​of-type.

以下是如何实现您想要的.从本质上讲,您选择的是所有奇数 <p>元素,兄弟姐妹(即之后<h2>标签).

h2 ~ p:nth-of-type(odd) {
  font-weight: 600;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <h2>This is a title cat</h2>
  <p>This is a message</p>
  <p>One cat</p>
  <p>Two cat</p>
  <p>Three cat</p>
  <h2>This is a title dog</h2>
  <p>Dog 0</p>
  <p>Dog 1</p>
  <p>Dog 2</p>
  <p>Dog 3</p>
</div>
Run Code Online (Sandbox Code Playgroud)