nth-child(2):第 2 个子元素
nth 表示“第 n 个”,child 表示“子元素”;括号里的 2 指定位置,计数从 1 开始。
本例 section 的子元素依次是:① h2、② 唱腔 p、③ 服饰 p、④ div。h2 也要计数,空格和换行不计。
:nth-child(2) 是结构伪类,匹配在自己的父元素中排第 2 位的子元素。
<section class="events">
<h2>活动</h2>
<p class="item">唱腔</p>
<p class="item">服饰</p>
<div>
<p class="item">舞台</p>
</div>
</section>
nth 表示“第 n 个”,child 表示“子元素”;括号里的 2 指定位置,计数从 1 开始。
本例 section 的子元素依次是:① h2、② 唱腔 p、③ 服饰 p、④ div。h2 也要计数,空格和换行不计。
.events > .item {
border-left: 4px solid teal;
padding-left: 12px;
}
“唱腔”和“服饰”有青绿色左边框,文字与左边框之间留 12px 内边距;“舞台”不匹配。
.events > .item:nth-child(2) {
color: crimson;
}
在 .events 的直接子元素中,第 2 个是“唱腔”,它又带有 item 类,所以文字变为深红色。
<style>
.events > .item {
border-left: 4px solid teal;
padding-left: 12px;
}
.events > .item:nth-child(2) {
color: crimson;
}
</style>
<section class="events">
<h2>活动</h2>
<p class="item">唱腔</p>
<p class="item">服饰</p>
<div>
<p class="item">舞台</p>
</div>
</section>