如何在c2中发生h2元素后对每个奇数p元素进行样式化? [英] How to style every odd p element after h2 element occured in css?
问题描述
我有一个HTML是乱糟糟的,我不能改变它,它看起来像这样:
< div>
< h2>这是标题cat< / h2>
< p>这是一封邮件< / p>
< p>一只猫< / p>
< p>两只猫< / p>
< p>三只猫< / p>
< h2>这是标题狗< / h2>
< p>狗0< / p>
< p>狗1< / p>
< p>狗2< / p>
< p>狗3< / p>
< / div>
现在我想做一个h2元素更大的每一个奇数p。
所以我想这是大胆:
这是一个消息
两只猫
狗0
狗2
如何在CSS中编写一个选择器(没有jQuery,没有可用的JS)使这些文本粗体?
您可以使用css 〜
选择器,然后使用 nth-of-type
或 nth-child
)选择器。您可以在MDN上详细了解这些选择器: 一般兄弟姐妹选择器 和 :nth-of-type 。
这里是如何实现你想要的。基本上,您选择的是兄弟姐妹的所有奇 < p>
元素
h2〜p:nth-of-type(odd){font-weight:600;}
< div> < h2>这是标题cat< / h2> < p>这是一封邮件< / p> < p>一只猫< / p> < p>两只猫< / p> < p>三只猫< / p> < h2>这是标题狗< / h2> < p>狗0< / p> < p>狗1< / p> < p>狗2< / p> < p>狗3< / p>< / div>
I have a HTML that is messed and i can not change it, it looks like this:
<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>
Now i would like to make every odd p that comes after a h2 element bolder. So i would like this to be in bold:
This is a message
Two cat
Dog 0
Dog 2
How to write a selector in CSS (no jQuery, no JS available) to make those texts bold?
You can do this by using the css ~
selector, followed by the nth-of-type
(alternatively nth-child
) selector. You can read more about it these selectors on the MDN: General Sibling Selector and :nth-of-type.
And here's how to achieve what you wanted. Essentially, you're selecting all odd <p>
elements that are siblings (i.e that come after) an <h2>
tag.
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>
这篇关于如何在c2中发生h2元素后对每个奇数p元素进行样式化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!