所以,我遇到了以下问题。我正在尝试使用 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; }
关于css - 未应用第 n 个子样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759439/