我有一个乱七八糟的 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>
现在我想让 h2 元素后面的每个奇数 p 都更粗。 所以我希望这是粗体:
This is a message
Two cat
Dog 0
Dog 2
如何在 CSS 中编写一个选择器(没有 jQuery,没有可用的 JS)来使这些文本加粗?
最佳答案
您可以使用 css ~
来做到这一点选择器,后跟 nth-of-type
(或者 nth-child
)选择器。您可以在 MDN 上阅读这些选择器的更多信息:General Sibling Selector和 :nth-of-type .
下面是如何实现您想要的。本质上,您选择了所有奇数 <p>
属于兄弟(即之后)<h2>
的元素标签。
h2 ~ p:nth-of-type(odd) {
font-weight: 600;
}
<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>
关于html - 如何在 css 中出现 h2 元素后设置每个奇数 p 元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408456/