2016-09-07 69 views
3

我想選擇最後一個嵌套元素,而不管元素的類型如何。如何選擇元素中的最後一個元素,而不管CSS中的類型是什麼?

例子:

<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元素的最後一個嵌套元素。

+0

「的直接後代,最後孩子沒有按」 t似乎在做詭計「你確定嗎?你怎麼使用它? – BoltClock

回答

4

使用此:

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

說明:

這工作,因爲當你使用:

>它選擇直接孩子

*這個選擇所有元素

nth-child確保所有的直接子女都將成爲目標(如果您使用nth-of-type則不是這種情況。

+0

沒有任何解釋,仍然人們傾向於upvote這個答案,我覺得這個了不起的 – dippas

+0

不言自明...我首先回答@dippas:D – kukkuz

+1

這不是一個「我先回答」的問題,這是一個「好內容「,http://meta.stackexchange.com/questions/9731/fastest-gun-in-the-west-problem - 順便說一句,我沒有downvote你 – dippas

3

可以使用section >*:last-child,其中*是通用選擇和>爲孩子選擇,只意味着將適用於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>

相關問題