如何选中嵌套在.positions容器中的每第二个<p>元素并修改背景色
问题描述
- 需求:给每第二个
<p>元素设置背景色,每个<p>都被class为positions的div包裹,所有5个该div都包含在class为bottom-section的div中 - 问题:使用伪类选择器尝试后无效果
相关代码
HTML代码
<div class="bottom-section"> <div class="positions position-1 hidden"> <p class="text-1"></p> </div> <div class="positions position-2 hidden"> <p class="text-2 even"></p> </div> <!-- 剩余3个positions结构类似 --> </div>
尝试的CSS代码
.positions p:nth-child(even) { background-color: rgba(22, 22, 190, 0.8); }
解决方案
你的CSS失效原因是:p:nth-child(even)是在每个.positions容器内部选择第偶数个<p>,但每个.positions里只有一个<p>,所以永远匹配不到目标元素。
正确的做法是先选中.bottom-section下的偶数个.positions容器,再选择容器内的<p>元素:
.bottom-section .positions:nth-child(even) p { background-color: rgba(22, 22, 190, 0.8); }
如果你的.bottom-section下还有其他非.positions的子元素,建议改用nth-of-type(even)来精准匹配div类型的子元素:
.bottom-section .positions:nth-of-type(even) p { background-color: rgba(22, 22, 190, 0.8); }
内容的提问来源于stack exchange,提问作者Piotr Ruszkiewicz
相关产品推荐
相关产品推荐

