CSS select direct children, but not if inside another nested child

Issue

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 :

  1. Select the children .child but not the ones inside the
    div.ignore-me?

  2. 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>

Solution

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>

Answered By – j08691

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.