【问题标题】:nth-child style not applied未应用第 n 个子样式
【发布时间】:2013-12-24 18:56:45
【问题描述】:

所以,我遇到了以下问题。我正在尝试使用 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; }

没有&lt;h1&gt;,它可以完美运行,检查这个Fiddle

但是对于&lt;h1&gt;,似乎将&lt;h1&gt; 视为&lt;p&gt;。使最后一个“标题”没有颜色。检查Fiddle

我不明白为什么会这样。

【问题讨论】:

  • 没有第四个孩子&lt;p&gt;。你可能想要nth-of-type
  • nth-child 实际上在父容器中做元素 - 它没有考虑选择器

标签: css css-selectors pseudo-class


【解决方案1】:

因为如果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; }

Demo

【讨论】:

  • 啊,有时候就是这么简单。谢谢!
【解决方案2】:

通过添加另一个元素(&lt;h1&gt;),您在选择器中使用的索引现在减 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 伪类,它会考虑实际元素,正如 Alien 先生的回答中所示。

【讨论】:

    猜你喜欢
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2020-12-12
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多