CSS select first-of-type amongst grandchildren?

2019-02-17 04:42发布

问题:

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 this HTML structure:

<div class="parent">
    <div>
        <p class="interline"><!-- only this -->
        <p class="interline">
        <p class="interline">
    </div>
    <div>
        <p class="interline">
        <p class="interline">
        <p class="interline">
    </div>
</div>

And want to select only the first grandchild <p> under the .parent div.

How do I do that?

回答1:

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



回答2:

.parent > div:first-child > p:first-child

Here you go, this should work for you



回答3:

It would be .parent p.interline:first-child or .parent .interline:first-child.