You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS nth-of-type选择器异常:奇数生效偶数失效求助

问题分析与解决方案

问题根源

你当前的CSS选择器逻辑错误:每个.post-container容器内仅包含1个文章div,因此每个文章div都是其容器下的第1个(odd)子元素,偶数规则nth-of-type(even)永远无法匹配到任何元素。

修正后的CSS代码

将nth-of-type选择器应用到.post-container层级(即.posts的直接子元素),再选中内部的文章div,即可实现背景色交替效果:

/* 奇数位置文章的背景样式 */
.posts .post-container:nth-of-type(odd) > div {
  background: red;
  padding: 68px;
}

/* 偶数位置文章的背景样式 */
.posts .post-container:nth-of-type(even) > div {
  background: blue;
}

额外排查建议

  • 打开浏览器开发者工具(F12),在元素面板中查看目标元素,确认修正后的CSS规则是否被正确加载,是否存在更高优先级的样式覆盖当前规则
  • 若样式仍不生效,可提升选择器权重,例如结合父元素ID:#posts .post-container:nth-of-type(even) > div
  • 确认所有.post-container都是.posts的直接子元素,无其他同级元素干扰nth-of-type的计数逻辑

内容的提问来源于stack exchange,提问作者Mahi99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:05:32