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

CSS样式在深色主题不生效::nth-of-type选中元素边框未显示

问题描述

我尝试使用:nth-of-type选择器,根据元素的class和索引来高亮特定元素。但看不到单词“for”周围的指定边框,Chrome开发者工具显示样式已应用,但实际显示不出来,请问哪里出错了?

原CSS代码

.verse {
  display: block;
  margin-top: 2em;
  margin-bottom: 2em;
}

.line {
  display: block;
}

.word {
  display: inline;
}

.beat {
  display: inline;
}

.verse .line .beat:nth-of-type(3) {
  border-width: 1px;
  border-color: yellow;
  border-style: solid;
}

原HTML代码

<div class="song">
  <div class="verse">
    <div class="line">
      <div class="word">
        <div class="beat">His</div>
        <div class="beat">t'ry</div>
      </div>
      <div class="word">
        <div class="beat">for</div>
      </div>
      <div class="word">
        <div class="beat">10's</div>
      </div>
      <div class="word">
        <div class="beat">ans</div>
        <div class="beat">wer</div>
      </div>
      <div class="word">
        <div class="beat">is</div>
      </div>
    </div>
  </div>
</div>

问题分析与修复方案

核心问题

  1. 选择器逻辑错误::nth-of-type是按父元素下的同类型子元素计数,不是按class筛选后计数。你的.beat都是.word的子元素,.line的直接子元素是.word,所以.verse .line .beat:nth-of-type(3)根本匹配不到任何元素——.line下没有直接的.beat子元素。
  2. 行内元素边框显示异常:你给.beat设置了display: inline;,行内元素的边框会和文本基线对齐,垂直方向的边框容易被遮挡或显示不完整,即使样式被应用也可能看不到。

修复步骤

1. 修正选择器

要选中“for”所在的.beat,可以定位到它的父元素——.line下的第2个.word,再选中其中的.beat:

.verse .line .word:nth-child(2) .beat {
  border-width: 1px;
  border-color: yellow;
  border-style: solid;
}

2. 调整元素显示类型

把.beat的display改为inline-block,让边框能正常显示:

.beat {
  display: inline-block;
}

修复后的完整CSS

.verse {
  display: block;
  margin-top: 2em;
  margin-bottom: 2em;
}

.line {
  display: block;
}

.word {
  display: inline;
}

.beat {
  display: inline-block;
}

.verse .line .word:nth-child(2) .beat {
  border-width: 1px;
  border-color: yellow;
  border-style: solid;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:45:05