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

为何CSS选择器p:nth-child(1)在HTML中失效?br标签是否为诱因?

问题:p:nth-child(1)选择器未生效的原因及解决办法

我在<style>标签中使用代码p:nth-child(1){color: white;}后未生效。预期HTML中的第一个<p>标签文字显示为白色,但实际呈现黑色。移除<body>中的<br>标签后,该<p>标签的颜色变为白色。相关代码如下:

<style>
body {
  background-color: #162b85;
}

button,
p:nth-child(1) {
  color: white;
}
</style>

<br />
<p class="center">Register your account</p>
<div class="container">
    <button type="submit" class="color">Sign up</button>
  <p class="center">Already have an account? <a href="#">Sign in</a>.</p>
</div>

原因分析

p:nth-child(1)的逻辑是选中某个父元素下的第1个子元素,且这个元素必须是<p>标签。你的代码里,<br>是<body>的第一个子元素,目标<p>是<body>的第二个子元素,所以这个选择器根本匹配不到目标元素,样式自然不生效。

解决办法

  • 方案一:改用p:first-of-type选择器,它会忽略父元素下的其他类型元素,直接选中第一个<p>标签:
    button,
    p:first-of-type {
      color: white;
    }
    
  • 方案二:调整选择器为p:nth-child(2),直接匹配<body>下的第二个子元素(也就是目标<p>):
    button,
    p:nth-child(2) {
      color: white;
    }
    
  • 方案三:如果页面不需要这个<br>标签,直接删除它,原来的p:nth-child(1)就能正常匹配目标<p>。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:02:26