如何在c2中发生h2元素后对每个奇数p元素进行样式化? [英] How to style every odd p element after h2 element occured in css?

查看:171
本文介绍了如何在c2中发生h2元素后对每个奇数p元素进行样式化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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> 元素



lang =jsdata-hide =falsedata-console =true>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆