【问题标题】:How to select the last element within an element regardless of type in CSS?无论CSS中的类型如何,如何选择元素中的最后一个元素?
【发布时间】:2016-09-07 19:19:35
【问题描述】:

无论元素的类型如何,我都想选择最后一个嵌套元素。

例子:

<section>
    <div></div>
    <p></p>
    <div></div> <-- I want this element
</section>
<section>
    <div></div>
    <p></p>
    <a></a>     <-- I want this element
</section>
<section>
    <div></div>
    <p></p>
    <ul>        <-- I want this element
        <li></li>
    </ul>
</section>

如何获得这些元素? :last-child 似乎没有用,:last-of.type 也没有帮助,因为我必须指定我想要的元素类型。

我想要section 元素的最后一个嵌套元素。

【问题讨论】:

  • ":last-child 似乎没有成功" 你确定吗?你是怎么用的?

标签: html css css-selectors


【解决方案1】:

使用这个:

section > *:last-child {
    // your custom css styles
}

说明:

这是有效的,因为当您使用时:

&gt;它选择直接的孩子

* 这会选择所有元素

nth-child 确保所有直系子代都将成为目标(如果您使用 nth-of-type,则情况并非如此。

【讨论】:

    【解决方案2】:

    您可以使用section &gt;*:last-child,其中* 是通用选择器,&gt; 是子选择器,这意味着仅适用于section 的直系后代

    section {
      color: blue
    }
    section > *:last-child {
      color: red
    }
    <section>
      <div>blue</div>
      <p>blue</p>
      <div>red</div>
      <!-- I want this element -->
    
    </section>
    <section>
      <div>blue</div>
      <p>blue</p>
      <a>red</a>
      <!-- I want this element -->
    
    </section>
    <section>
      <div>blue</div>
      <p>blue</p>
      <ul>
        <!-- I want this element -->
    
        <li>red</li>
      </ul>
    </section>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2013-08-18
      • 1970-01-01
      • 2016-04-20
      • 2016-01-30
      • 1970-01-01
      • 2020-01-21
      相关资源
      最近更新 更多