How can I select only elements which are first children of a container by class?

Viewed 281

I have complex blocks of DIVs netted to one another and I cannot edit them because this html code is provided from the system. Only thing I could do is from CSS.

I want to select only "Child 1". My CSS does select "Child 1", but because of some related class netted to one another, it selects "Grand child 1" and "Great grandChild 1", as well, unfortunately!

Please give me a hand on how to select only "Child 1".

Thanks!

.container > .child:first-child {
  border: 1px solid red;
}
<div class="container">
Parent
  <div class="child">
    Child 1
  </div>
  <div class="child">
    Child 2
     <div class="container">
        Child of Child 2
        <div class="child">
          Grand Child 1
        </div>
        <div class="child">
          Grand Child 2
          <div class="container">
            Parent
              <div class="child">
                Great grandChild 1
              </div>
                <div class="child">
                  Great grandChild 2
              </div>
            </div>
        </div>
      </div>
  </div>
</div>

2 Answers

This will only select .container that not child of the .child.

:not(.child) > .container > .child:first-child {
  border: 1px solid red;
}
<div class="container">
Parent
  <div class="child">
    Child 1
  </div>
  <div class="child">
    Child 2
     <div class="container">
        Child of Child 2
        <div class="child">
          Grand Child 1
        </div>
        <div class="child">
          Grand Child 2
          <div class="container">
            Parent
              <div class="child">
                Great grandChild 1
              </div>
                <div class="child">
                  Great grandChild 2
              </div>
            </div>
        </div>
      </div>
  </div>
</div>

.child:first-child:is(:not(.child *)) will select elements with class child which are first element children of their parents and have no ancestors with class child.

Related