Reputation: 4469
I want to find how to select the .if-first-child
element that's the first element of a specific parent, which in this case is <div>
.
<div class="no-css">
<p class="if-first-child">The style will only take effect here!</p>
<p>No style here..</p>
<p class="if-first-child">No style here..</p>
</div>
<div class="no-css">
<nav>
<p class="if-first-child">No style here..</p>
</nav>
</div>
In other words, e.g. I want to apply background-color: black;
in the .if-first-child
only if it's the first child of <div>
.
Keep note that the div p:first-child
selector will still select the .if-first-child
element even though it have a <nav>
parent.
Upvotes: 0
Views: 73
Reputation: 1
In simple, you can try this as well...
.if-first-child{color:red}
div .if-first-child{color:green}
It will target only first child to change the color of the text and rest will apply default text color.
Upvotes: 0
Reputation: 4469
Unintended, I found how to select the target when I'm exposing in the question that the div p:first-child
selector will still select the p:first-child
element if it have a <div>
grandparent.
div > .if-first-child:first-child {
background-color: black;
}
That will only target the first-child .if-first-child
which is a direct child of <div>
. It will not target a grandchild .if-first-child:first-child
.
Upvotes: 1