css - 未应用第 n 个子样式

标签 css css-selectors pseudo-class

所以,我遇到了以下问题。我正在尝试使用 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> ,它完美地工作,检查这个 Fiddle .

但是有了 <h1> , 似乎看到了 <h1>作为<p> .使最后一个“标题”没有颜色。检查Fiddle .

我不明白为什么会这样。

最佳答案

因为如果nth-child没有找到第 nth 个元素匹配 p 元素,所以它会失败,使用 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

关于css - 未应用第 n 个子样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759439/

相关文章:

jquery - SlideToggle 导航菜单消失得太快

html - 另一个元素内的 css 选择器

css - 将 css 添加到第一个 child 和下一个 child 样式?

html - 带有否定伪类的用户操作伪类

css - 使用 Stylus mixin 定义 React CSSTransitionGroup 动画

javascript - 修改元素 :before CSS rules programmatically in React

html - 在 flexbox 中将文本居中放置在图像上

css - 选择偶数 div child 的 child

jquery - 循环遍历jquery中的元素集

css - 在 Sass 中使用带有变量的伪类