nth-of-type vs nth-child

后端 未结 7 1182
梦谈多话
梦谈多话 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:03

    The nth-child pseudo-class refers to the "Nth matched child element", meaning if you have a structure as follows:

    Hello

    Paragraph

    Target

    Then p:nth-child(2) will select the second child which is also a p (namely, the p with "Paragraph").
    p:nth-of-type will select the second matched p element, (namely, our Target p).

    Here's a great article on the subject by Chris Coyier @ CSS-Tricks.com


    The reason yours breaks is because type refers to the type of element (namely, div), but the first div doesn't match the rules you mentioned (.row .label), therefore the rule doesn't apply.

    The reason is, CSS is parsed right to left, which means the the browser first looks on the :nth-of-type(1), determines it searches for an element of type div, which is also the first of its type, that matches the .row element, and the first, .icon element. Then it reads that the element should have the .label class, which matches nothing of the above.

    If you want to select the first label element, you'll either need to wrap all of the labels in their own container, or simply use nth-of-type(3) (assuming there will always be 2 icons).

    Another option, would (sadly) be to use... wait for it... jQuery:

    $(function () {
        $('.row .label:first')
            .css({
                backgroundColor:"blue"
            });
    });
    

提交回复
热议问题