CSS select first-of-type amongst grandchildren?

后端 未结 3 465
别那么骄傲
别那么骄傲 2021-01-12 00:15

I\'ve read tricky questions such as Select first Descendant with CSS or How do I hide only the first element of a type? but mine doesn\'t match these ones.

I have th

3条回答
  •  花落未央
    2021-01-12 00:48

    You need to select the first div as well

    .parent > div:first-of-type > p:first-of-type {
        color: red;
    }
    

    Demo

    Here in the above selector, I am selecting the first p element nested inside the first div, which is further nested as direct child to an element having a class of .parent

    > means select direct descendant to it's parent.


    The above will fail in older versions of Internet Explorer, so if you are looking to support them as well, than equivalent supported selector will be

    .parent > div:first-child > p:first-child {
        color: red;
    }
    

    Demo (Supports IE7 as well)

    But using :first-child and :first-of-type has huge difference, say you are using p:first-child and you have some other element apart from p, your selector will fail, so that's why I provided you a solution of using :first-of-type

提交回复
热议问题