如何选择页面中的最后一个元素?

问题描述 投票:0回答:2

有没有办法用CSS选择特定元素的最后出现?

这是一个例子:DEMO

我尝试过

last-child
但这不是我想要的。我用过这个课程:

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;
}

我希望最后一个带有“红色”内容的

span
是红色的。我怎样才能用CSS做到这一点?

更新: 对于具有相同父元素的元素,有一个使用

last-of-type
的解决方案。但不同的父母呢?

css css-selectors
2个回答
6
投票

试试这个:(你应该知道父包装元素

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

工作小提琴


0
投票

这是从我的博客中获取的解决方案: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>

一个更复杂的例子:

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>

© www.soinside.com 2019 - 2024. All rights reserved.