我想使用外部CSS更新/触摸HTML中第一次出现的元素。例如:
<section>
<article>
<h2>20 CSS Best Practices</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>CSS References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>Additional References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
</section>
&#13;
在上面的代码中,我只希望仅在第一个<h2>
中触摸article
的第一个匹配项,而不是在所有articles
中。
但是使用first-of-type会更新所有<h2>
。我知道有一种方法可以通过类或ID属性更新它,但我不想这样做。还有其他办法吗?
答案 0 :(得分:2)
使用nth-of-type
获取相同的
添加以下css部分
section article:nth-of-type(1) h2 {
color: red;
}
section article:nth-of-type(1) h2 {
color: red;
}
&#13;
<section>
<article>
<h2>20 CSS Best Practices</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>CSS References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>Additional References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
</section>
&#13;
您也可以使用first-of-type
来获取
section article:first-of-type h2{
color: red;
}
&#13;
<section>
<article>
<h2>20 CSS Best Practices</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>CSS References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>Additional References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
</section>
&#13;
first-child
也可以使用
section article:first-child h2 {
color: red;
}
&#13;
<section>
<article>
<h2>20 CSS Best Practices</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>CSS References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
<article>
<h2>Additional References</h2>
<p>
<ul>
<li>ABC</li>
<li>XYZ</li>
</ul>
</p>
</article>
</section>
&#13;