Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 827
user7607751 Avatar asked Mar 03 '23 05:03

user7607751


1 Answers

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>
like image 58
j08691 Avatar answered Apr 30 '23 01:04

j08691