Mohsen Safari
Mohsen Safari

Reputation: 6795

how to select last element in the page?

is there any way to select last appear of a specific element with css?

this is an example: DEMO

i tried last-child but this is not what i want. i used this class:

HTML:

<ul>
    <li><span>test</span></li>
    <li>
        <span>test</span>
        <span>test</span>
    </li>
</ul>
<div>
    <span>test</span>
    <span>test</span>
</div>
<p>
    <span>test</span>
    <span>red</span>
</p>

CSS:

span:last-child{
    color:red;
    font-weight:bold;
}

i want the last span with "red" content to be red. how i can do it with css ?

update: there is a solution with last-of-type for elements with same parents. but what about different parents ?

Upvotes: 1

Views: 5318

Answers (2)

Temani Afif
Temani Afif

Reputation: 274384

Here is a solution taken from my blog: https://css-tip.com/last-element-dom/

span {
  &:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
    color: red;
    font-weight: bold;
  }
}
<ul>
  <li><span>test</span></li>
  <li>
    <span>test</span>
    <span>test</span>
  </li>
</ul>
<div>
  <span>test</span>
  <span>test</span>
</div>
<p>
  <span>test</span>
  <span>red</span>
</p>

A more complex example:

span {
  &:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
    color: red;
    font-weight: bold;
  }
}
<div>Some content</div>
<div>
  <span>Some content</span>
  <span>
    <span>Some content</span>
    <span>Some content</span>
    <span>Some content</span>
  </span>
  <span>Some content</span>
  <span>Some content</span>
</div>
<div>
  <span>Some content</span>
  <span>Some content</span>
</div>
<span>
  <span>Some content</span>
  <span>Some content</span>
</span>
<div>
  <span>
    <span>Some content</span>
    <span>Some content</span>
  </span>
  <span>
    <span>Some content</span>
    <span>Some content</span>
    <span>Some content</span>
  </span>
  <span>
    <span>Some content</span>
    <span>Some content</span>
    <span>Some content
      <span>Some content</span>
      <span>Some content</span>
    </span>
    <span>
      <span>
        <span>
          <span>Some content</span>
          <span>Some content</span>
          <span>Some content</span>
        </span>
      </span>
    </span>
    <span>
      <span>Some content</span>
      <span>Some content</span>
      <span>Some content</span>
    </span>
  </span>

Upvotes: 0

Mr_Green
Mr_Green

Reputation: 41872

Try this: (you should be aware of the parent wrapper element)

body > *:last-child > span:last-child{
    color: red;
}

Working Fiddle

Upvotes: 6

Related Questions