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

为何:first-child和:last-child伪选择器无法选中div元素?

伪选择器失效与环境显示差异问题解析

一、:first-child/:last-child失效原因

:first-child 和 :last-child 的匹配逻辑是选中父元素下第一个/最后一个子元素,且该子元素是目标类型(这里是div)。如果父元素下的第一个/最后一个子元素不是div,这两个选择器就不会生效:

  • 比如页面<body>标签下先有<link>、<script>或其他非div元素,第一个div就不是<body>的:first-child;
  • 如果<body>末尾还有其他元素(如脚本、版权信息),最后一个div也不是<body>的:last-child。

而:nth-child()、:last-of-type不受此限制:

  • :nth-child(n)只要父元素下第n个子元素是div就会匹配;
  • :last-of-type直接选中父元素下所有div类型里的最后一个,无需考虑父元素其他子元素。

二、解决方案

方案1:改用:first-of-type/:last-of-type

这两个选择器专门匹配父元素下同类型元素的第一个/最后一个,无需依赖父元素的整体子元素顺序,适配性更强:

div:first-of-type {
  background-color: darksalmon;
  padding-bottom: 10px;
}

div:last-of-type {
  background-color: black;
  padding-bottom: 10px;
}

方案2:给目标div添加统一容器

将所有div放在一个独立容器内,确保容器内只有这些div,此时:first-child/:last-child就能精准匹配:

<div class="container">
  <div>
    <h1>Hex to Binary</h1>
    <input type="text" placeholder="Insert your hexidecimal value" />
    <input type="Button" value="Convert" />
  </div>
  <div>
    <h1>Binary to Hex</h1>
  </div>
</div>
.container div:first-child {
  background-color: darksalmon;
  padding-bottom: 10px;
}

.container div:last-child {
  background-color: black;
  padding-bottom: 10px;
}

三、VS Code Live Server与JSFiddle显示差异原因

两个环境的页面整体结构不同:

  • JSFiddle的沙箱环境会将你输入的HTML代码直接插入到纯净的<body>容器中,默认没有额外前置/后置元素,此时div可能刚好是父元素的第一个/最后一个子元素,:first-child/:last-child能生效;
  • VS Code Live Server加载的是你本地完整的HTML文件,若文件中<body>包含其他元素(如头部样式引用、尾部脚本),会导致div无法满足父元素第一个/最后一个子元素的条件,选择器失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:20:13