CSS3获取最后一个元素 [英] CSS3 get last element

查看:2806
本文介绍了CSS3获取最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从以下代码中获取最后一个元素(hr):

 < div& 
< div>
< span class =hr>< / span>
< / div>

< div>
< span class =hr>< / span>
< / div>

< div>
< span class =hr>< / span> <! - 我需要这 - >
< / div>
< / div>

.hr:last-child t为此工作。



当然,DOM结构可能更复杂。我只需要获取最后一个需要的元素。

解决方案

有几种方法可以从你的例子中获得最后的 .hr 元素,但你说DOM结构可能更复杂。为了回答你的问题,你需要提到你可能有什么可能的DOM结构;



这里有一种获取 .hr 最后的 div

  div div:last-of -type .hr 

这是另一种获取 .hr 外部 div 的最后一个子项之外:

  div:last-child .hr 



如果您需要获取最后的 .hr 元素,不管它在里面,那么你不能在CSS中做。在CSS中,您只能在层次结构的某个特定级别选择第一个,最后一个或 n 个元素,不能选择某种类型的最后一个元素,而不管它嵌套在什么位置。 / p>

How I can get the last element (hr) from the following code:

<div>
    <div>
        <span class="hr"></span>
    </div>

    <div>
        <span class="hr"></span>
    </div>

    <div>
        <span class="hr"></span> <!-- I need this -->
    </div>
</div>

.hr:last-child doesn't work for this.

Of course, DOM structure could be more complicated. I just need to fetch the last needed element.

解决方案

Your question isn't quite clear; there are several ways to get the last .hr element from your example, but you say "DOM structure could be more complicated." In order to answer your question, you need to mention what possible DOM structures you could have; in some it might be possible, in some it will not be.

Here is one way to get the .hr out of the last div:

div div:last-of-type .hr

Here's another way to get the .hr out of the last child of the outer div:

div :last-child .hr

If you need to get the last .hr element out of the document, regardless of what it's inside, then you can't do that in CSS. In CSS, you can only select the first, last, or nth element at one particular level of the hierarchy, you can't select the last element of some type regardless of what it's nested in.

这篇关于CSS3获取最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆