nth-of-type vs nth-child

后端 未结 7 1180
梦谈多话
梦谈多话 2020-11-22 02:30

I am a bit confused about the nth-of-type pseudo class, and how this is supposed to work - especially as compared to the nth-child class.

M

7条回答
  •  醉梦人生
    2020-11-22 03:21

    :nth-of-type is used to select a sibling of a particular type. By type I mean a type of tag as in

  • , ,
    etc.

    :nth-child is used to select children of a particular parent tag without regard to a type

    Example of :nth-of-type

    HMTL:

      
    • Item 1
    • Item 2
    • Item 3
    • Item 4
    • Item 5
    • Item 6
    • Item 7
    • Item 8
    • Item 9
    • Item 10
    • Item 11
    • Item 12
    • Item 13
    • Item 14
    • Item 15
    • Item 16

    CSS:

    Notice that there is no space between the

  • tag and the pseudo-class nth-of-type.

    li:nth-of-type(odd) { background-color: #ccc; }

    Result: https://jsfiddle.net/79t7y24x/

    Example of :nth-child

    HTML:

      
    • Item 1
    • Item 2
    • Item 3
    • Item 4
    • Item 5
    • Item 6
    • Item 7
    • Item 8
    • Item 9
    • Item 10
    • Item 11
    • Item 12
    • Item 13
    • Item 14
    • Item 15
    • Item 16

    CSS:

    Notice here that there is a space between the

      tag and the :nth-child pseudo-class

      ul :nth-child(even) { background-color: red }

      Result: https://jsfiddle.net/o3v63uo7/

提交回复
热议问题