如何在包含多层嵌套div的animationbg类容器中单独选中指定p元素
选择器失效原因
nth-of-type()和nth-child()的匹配范围是当前元素的同级兄弟元素,而非整个父容器内的所有同类型元素。你直接写.animationbg p:nth-of-type(1)会选中每个p所在父容器下的第一个p,无法实现全局按顺序选中的需求。
可用选择方案
方案1:全兼容方案(兼容所有新旧浏览器)
通过上层sppb-addon-wrapper的序号定位,选择器如下:
- 第1个p(内容:Meta tag TITLE):
.animationbg .sppb-addon-wrapper:nth-of-type(2) p:nth-of-type(1) - 第2个p(内容:Meta tag TITLE 2):
.animationbg .sppb-addon-wrapper:nth-of-type(2) p:nth-of-type(2) - 第3个p(内容:Meta tag DESCRIPTION):
.animationbg .sppb-addon-wrapper:nth-of-type(3) p - 第4个p(内容:h1 h2 h3):
.animationbg .sppb-addon-wrapper:nth-of-type(4) p - 第5个p(内容:URL Rewrite):
.animationbg .sppb-addon-wrapper:nth-of-type(5) p - 第6个p(内容:Sitemap):
.animationbg .sppb-addon-wrapper:nth-of-type(6) p
注:你提到共有5个p,可根据实际展示的内容调整对应的序号即可。
方案2:简洁跨父级选择方案(兼容Chrome 111+、Firefox 113+、Safari 9+)
使用CSS的of语法直接匹配整个.animationbg容器内的第n个p元素:
- 选择第n个p:
.animationbg p:nth-child(n of p)
比如选中第3个p直接写:.animationbg p:nth-child(3 of p)
内容的提问来源于stack exchange,提问作者Dave Max
相关产品推荐
相关产品推荐

