Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS select first-of-type amongst grandchildren?

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?

like image 900
maxxyme Avatar asked Mar 17 '14 18:03

maxxyme


2 Answers

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

like image 83
Mr. Alien Avatar answered Oct 22 '22 22:10

Mr. Alien


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

Here you go, this should work for you

like image 3
Pinki Avatar answered Oct 22 '22 20:10

Pinki