不应用第 n 个子样式



所以,我遇到了以下问题。我试图使用 nth-child 给"标题"一种不同的颜色。

我的 HTML 看起来像这样:

<header>
    <h1>Title<br />
    <span>Subtitle</span></h1>
    <p><strong>Heading</strong><br />
    text</p>
    <p><strong>Heading</strong><br />
    text</p>
    <p><strong>Heading</strong><br />
    text</p>
</header>

我的CSS看起来像这样:

header h1 {
    font-size: 4em;
    line-height: .65em;
}
header h1 span {
    font-size: .5em;
}
header p {
    font-size: .9em;
}
header p strong {
    font-size: 1.1em;
}
header p:nth-child(1) strong { color: #f3b200; }
header p:nth-child(2) strong { color: #d27b26; }
header p:nth-child(3) strong { color: #dc572e; }

没有<h1>,它工作得很好,检查这个小提琴

但随着<h1>,它似乎将<h1>视为<p>。使最后一个"标题"没有颜色。检查小提琴

我不明白为什么会这样。

因为

如果nth-child没有找到p元素匹配的元素nth数量,那么它将失败,请改用nth-of-type

header p:nth-of-type(1) strong { color: #f3b200; }
header p:nth-of-type(2) strong { color: #d27b26; }
header p:nth-of-type(3) strong { color: #dc572e; }

演示

通过添加另一个元素(<h1> ),您在选择器中使用的索引现在偏离了 1。您可能已经注意到,第二个演示中的标题颜色也上移了一个位置。

您只需增加原始 CSS 上的索引即可选择新位置

header p:nth-child(2) strong { color: #f3b200; }
header p:nth-child(3) strong { color: #d27b26; }
header p:nth-child(4) strong { color: #dc572e; }

但更好的解决方案是使用不同的 CSS 选择器nth-of-type伪类,该选择器会考虑实际元素,如 Mr. Alien 的回答所示。

最新更新