选择第二个
article h1:nth-child(2) { // 第2个h1变红
color: red;
}
<article>
<h1>第1个h1</h1>
<h1>第2个h1</h1> // 这个变红了
<h1>第3个h1</h1>
<h1>第4个h1</h1>
</article>
奇数行变色
article h1:nth-child(2n) { // 奇数h1变红
color: red;
}
<article>
<h1>第1个h1</h1>
<h1>第2个h1</h1> // 这个变红了
<h1>第3个h1</h1>
<h1>第4个h1</h1> // 这个变红了
</article>
前2行变色
article h1:nth-child(-n+2) { // 前2个h1变红,**注意这里不能写成2-n,很神奇**
color: red;
}
<article>
<h1>第1个h1</h1> // 这个变红了
<h1>第2个h1</h1> // 这个变红了
<h1>第3个h1</h1>
<h1>第4个h1</h1>
</article>
后2行变色
article h1:nth-last-child(-n+2) { // 后2个h1变红,**注意这里不能写成2-n,很神奇**
color: red;
}
<article>
<h1>第1个h1</h1>
<h1>第2个h1</h1>
<h1>第3个h1</h1> // 这个变红了
<h1>第4个h1</h1> // 这个变红了
</article>
后3行变色,但排除后3行的倒数第2行
article h1:nth-last-child(-n+3):not(:nth-last-child(2)) {
color: red;
}
<article>
<h1>第1个h1</h1>
<h1>第2个h1</h1> // 这个变红了
<h1>第3个h1</h1> // 这个被排除了
<h1>第4个h1</h1> // 这个变红了
</article>