css選擇器之first-child和first-of-type的比較
阿新 • • 發佈:2020-12-22
技術標籤:csscssfirst-childfirst-of-type
定義:
:first-child 選擇器匹配其父元素中的第一個子元素。
:first-of-type 選擇器匹配元素其父級是特定型別的第一個子元素。
注意: :修飾的是當前元素,比如你想選p元素下的第一個span元素,你可以
p span:first-child : {}
// 或者sass寫法
p {
& span:first-child: {}
}
p:first-child: {} // 錯誤寫法
小例子
<div>
<p>我是p元素</p>
< h3>我是h3元素</h3>
</div>
// sass寫法
div {
& p:first-child {
color: red;
}
}
// 常規寫法
div p:first-child {
color: red;
}
效果:
但是如果想選第一個h3元素,上面這種寫法是不行的,要用:first-of-type
// sass寫法
div {
& h3:first-of-type {
color: red;
}
}
// 常規寫法
div p:first-of-type {
color: red;
}
所以,得出結論:
當需要設定的元素,是父元素的子元素,但是不是第一個子元素時,就要用first-of-type