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?
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
.parent > div:first-child > p:first-child
Here you go, this should work for you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With