CSS CSS3 获取最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3740949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:47:40  来源:igfitidea点击:

CSS3 get last element

csscss-selectors

提问by Alex Ivasyuv

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

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

<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-childdoesn't work for this.

.hr:last-child不适用于此。

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

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

回答by Brian Campbell

Your question isn't quite clear; there are several ways to get the last .hrelement 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.

你的问题不是很清楚;有几种方法可以.hr从您的示例中获取最后一个元素,但是您说“DOM 结构可能更复杂”。为了回答您的问题,您需要提及您可以拥有哪些可能的 DOM 结构;在某些情况下可能有可能,在某些情况下则不会。

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

这是.hr摆脱最后一个的一种方法div

div div:last-of-type .hr

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

这是从.hrexternal 的最后一个孩子中取出的另一种方法div

div :last-child .hr

If you need to get the last .hrelement 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.

如果你需要.hr从文档中取出最后一个元素,不管它里面是什么,那么你不能在 CSS 中做到这一点。在 CSS 中,您只能选择层次结构的一个特定级别的第一个、最后一个或第n个元素,您不能选择某种类型的最后一个元素,无论它嵌套在什么中。

回答by Delan Azabani

div:last-child .hr

回答by Dylan Gordon

The following selector should work:

以下选择器应该可以工作:

div *:last-child *:last-child

Demo: https://jsfiddle.net/78w3bofg/1/

演示:https: //jsfiddle.net/78w3bofg/1/