What is the difference between p:nth-child(2) and p:nth-of-type(2)?

前端 未结 8 2070
醉酒成梦
醉酒成梦 2020-12-10 03:37

What is the difference between p:nth-child(2) and p:nth-of-type(2)?

As per W3Schools CSS Selector Reference:

  • p:nth-chil
8条回答
  •  难免孤独
    2020-12-10 03:46

    As MDN says:

    The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.


    That means that p:nth-child(2) will only capture

    elements that are the second child of their parent.

    However, p:nth-of-type(2) will capture

    elements that are the second element of their parent, regardless of the element's index. This mean's an element can have 100 children and if the last child is the second paragraph element among its siblings, it will be affected by the styles listed.

    Some things to keep in mind (that haven't already been said):

    an element is nth-child(1) and nth-of-type(1)

    This is always true.


    an element is nth-child(2) and nth-of-type(2)

    This is true when an element's first 2 children are of the same type.


    an element is nth-child(3) and nth-of-type(2)

    This is true when an element's 1st and 3rd children are of the same type, but the 2nd child is not.


    an element is nth-child(2) and nth-of-type(3)

    This is always false as an element that is the 3rd of its type can not be the 2nd child of it's parent.


    Example:

    p:nth-child(2)   { color: red; }
    p:nth-of-type(2) { background-color: yellow; }

    Paragraph 1

    Paragraph 2


    Paragraph 1

    Paragraph 2

提交回复
热议问题