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

为何nth-child(even)无响应,nth-child(odd)却正常生效?

问题分析与解决

问题描述

制作中间轨道两侧交替排列的时间线时,为条目添加notes详情框,试图用:nth-child(odd/even)实现左侧条目对应notes左浮动、右侧条目对应notes右浮动的效果,但只有odd规则生效,even规则完全无响应,哪怕仅修改颜色也无效。

核心原因

当前使用的.notes:nth-child(odd/even)选择器,是在**每个.notes的父元素(单个.en容器)**范围内判断子元素奇偶性,但每个.en里的.notes都是第一个子元素,因此所有.notes都会匹配:nth-child(odd),:nth-child(even)永远找不到目标元素。

此前条目交替效果生效,是因为直接给.en使用:nth-child(even)——这是在.en的共同父元素范围内判断奇偶,逻辑正确;但现在把选择器层级套在.notes上,就完全偏离了原本的判断范围。

修正方案

将奇偶判断的层级移到父容器.en上,再选择其内部的.notes元素:

修正后的CSS代码

.notes {
  width: 55px;
  height: 1.5em;
  overflow: hidden;
  color: #fff000;
  z-index: 1;
  transition: 0.4s ease;
  position: absolute;
}
.notes:hover {
  height: auto;
  max-height: 150px;
  width: 350px;
  overflow: auto;
  padding: 10px;
}
/* 奇数位置的.en容器内的notes设置右定位(左浮效果) */
.en:nth-child(odd) .notes {
  right: calc(100% + 30px);
}
/* 偶数位置的.en容器内的notes设置左定位(右浮效果)+ 修改颜色 */
.en:nth-child(even) .notes {
  color: #000fff;
  left: calc(100% + 30px);
}

补充HTML修正

示例HTML中存在<p>标签未闭合的问题,会导致浏览器解析异常,修正后代码如下:

<div class="en">
  <div class="notes">
    <p>Insert Notes Here 1</p>
  </div>
  <h2>Title1</h2>
  <h3>Subtitle 1</h3>
</div>

<div class="en">
  <div class="notes">
    <p>Insert Notes Here 2</p>
  </div>
  <h2>Title 2</h2>
  <h3>Subtitle 2</h3>
</div>

额外提示

  • 确保所有.en容器都处于同一个父元素下,这样:nth-child(odd/even)才能正确判断整个时间线的条目顺序。
  • 如果.en的父元素还包含其他类型的子元素,建议改用:nth-of-type(odd/even)来精准匹配.en元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:54:57