📜  CSS 中 :first-child 和 :first-of-type 选择器的区别

📅  最后修改于: 2021-09-01 03:02:18             🧑  作者: Mango

它们都是 CSS 中用于选择特定子项的 HTML 的选择器。
:first-child: :first-child 选择器用于选择那些作为第一个子元素的元素。对于 :first-child 选择器,必须为 IE8 和更早版本声明 。

:first-of-type: :first-of-type Selector 用于定位其父元素的每个元素的第一个子元素。如果我们想在不提供类的情况下为元素的第一个子元素设置样式,我们可以使用它。

例子:



  

    :first-child and first-of-type selector
    

  

    

GeeksforGeeks

    

This is :first-child and first-of-type selector

    
        

I am the First Child

        

I am the first of type Child

        

I am the third Child

        

I am the fourth Child

    
     

输出:

:first-child 和 :first-of-type 选择器的区别:

:first-child :first-of-type
This selector only choose the define element if the the element is the first child of the parent. If the define element comes second position then this selector can not select that element. This selector chose the define element if the element comes 2nd, 3rd or 4th any place but have to be the first of it’s type.
In the above example you can see inside the div tag the childs are p, h4, h4 and p. If you change 1st p tag into a another tag then :first-child slector can not select any child. In the above example you can see inside the div tag the childs are p, h4, h4 and p. If you change 1st p tag into h4 tag then :first-of-child slector will select the fisrt child of that parent which is also be the first child of the define element.