Choosing the last child with a given type among different levels of elements

I have a dynamically created HTML snippet that might look something like this (but can have many different levels of nesting):

<div class="content">
    <div class="thing"></div>
    <div>
        <div class="thing"></div>
        <div class="thing"></div>
    </div>
    <div>
        <div>
            <div class="thing"></div>
            <div class="thing"></div>
        </div>
    </div>
    <div>
        <div class="thing"></div>
    </div>
</div>

I would like the CSS expression to select the last element with the class thing, which is a (not necessarily direct) child element .content.

:last-childor :last-of-typewill not work because they match if the element is the last child (of a certain type) of its parent, in which case it will match more than .thing.

Is there a CSS expression that I can use for this?

+4
source share
2 answers

, CSS, .

0

. , 4 . , div.

.content > .thing:last-child,
.content > :last-child > .thing:last-child,
.content > :last-child > :last-child > .thing:last-child,
.content > :last-child > :last-child > :last-child > .thing:last-child {
  background-color: red;
}
<div class="content">
  <div class="thing">.thing</div>
  <div>
    <div class="thing">.thing</div>
    <div class="thing">.thing</div>
  </div>
  <div>
    <div>
      <div class="thing">.thing</div>
      <div class="thing">.thing</div>
    </div>
  </div>
  <div>
    <div class="thing">.thing</div>
  </div>
</div>
Hide result
0

Source: https://habr.com/ru/post/1674523/


All Articles