Reputation: 505
So, if this is the HTML of an element:
<div class="parent">
<div class="ignore-me">
<p class="child">ignore me</p>
<p class="child">ignore me</p>
<p class="child">ignore me</p>
<!-- I don't know how many <p> gonna be here -->
</div>
<p class="child">paint me green</p>
<p class="child">paint me blue</p>
</div>
How can I :
Select the children .child
but not the ones inside the
div.ignore-me
?
Select them separately, based on their index order.
I tried to use a mix of >
and :nth-child(n)
like this:
.parent > .child:nth-child(1)
But, it doesn't work!
Can this be done only CSS?
.parent > .child:nth-child(1) {
background: green;
}
.parent > .child:nth-child(2) {
background: blue;
}
<div class="parent">
<div class="ignore-me">
<p class="child">ignore me</p>
<p class="child">ignore me</p>
<p class="child">ignore me</p>
<!-- I don't know how many <p> gonna be here -->
</div>
<p class="child">paint me green</p>
<p class="child">paint me blue</p>
</div>
Upvotes: 4
Views: 8988
Reputation: 355
div.parent>p.child:nth-child(2) {
background: green;
}
div.parent>p.child:nth-child(3) {
background: blue;
}
div.parent>p.child:nth-child(4) {
background: green;
}
we can slect odd and event children
div.parent>p.child:nth-child(odd) {
background: green;
}
div.parent>p.child:nth-child(even) {
background: red;
}
Upvotes: 1
Reputation: 1421
The accepted answer can be further simplified to div.parent > p
, because >
already only selects direct children.
div.parent > p {
color:green;
}
<div class="parent">
<div class="ignore-me">
<p>don't select me</p>
<p>don't select me</p>
<p>don't select me</p>
<!-- I don't know how many <p> gonna be here -->
</div>
<p>select me</p>
<p>select me too</p>
</div>
Regarding
Select them separately, based on their index order.
you can use :nth-child, but be aware that :nth-child
also counts <div class="ignore-me">
as a child of <div class="parent">
. So your first <p class="child">
is the second child. You can then use even
and odd
to alternate between the children.
div.parent > p {
color:green;
}
div.parent > p:nth-child(odd) {
color:blue;
}
<div class="parent">
<div class="ignore-me">
<p class="child">ignore me</p>
<p class="child">ignore me</p>
<!-- I don't know how many <p> gonna be here -->
</div>
<p class="child">paint me green</p>
<p class="child">paint me blue</p>
<p class="child">paint me green</p>
<p class="child">paint me blue</p>
</div>
Upvotes: 2
Reputation: 207861
Use div.parent > p.p
>
is the child combinator. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.
div.parent > p.p {
color:green;
}
<div class="parent">
<div class="ignore-me">
<p class="p">don't select me</p>
<p class="p">don't select me</p>
<p class="p">don't select me</p>
<!-- I don't know how many <p> gonna be here -->
</div>
<p class="p">select me</p>
<p class="p">select me too</p>
</div>
Upvotes: 8