2013-01-10 84 views
17

我知道你可以用:last-child來選擇最後的寒意。現在我需要選擇最後3個孩子的唯一的問題是孩子的量是不知道,所以我不能使用:nth-child,我知道有個東西叫:nth-last-child但我真的不能明白這是怎麼工作的選擇最後3個孩子

<div id="something"> 

    <a href="images/x.jpg" ><a/> 
    <a href="images/x.jpg" ><a/> 
    <!-- here some more 

    and than i need to select these --> 
    <a href="images/x.jpg" ><a/> 
    <a href="images/x.jpg" ><a/> 
    <a href="images/x.jpg" ><a/> 

</div> 

所以現在我需要一些這樣的事:

#something a:last-child{ 
    /* only now it needs to select 2 more a's that are before this child */ 
} 
+1

':第n-最後child',基本相同':第n-child'但數從去年到第一AFAIK。 –

+0

現在的問題是需要選擇最後3個 – Ivo

+0

P.S.結束標籤是'

'而不是'
'。 –

回答

59

你可以閱讀第n-最後一個孩子更here,但是這主要應該做的只是CSS

#something a:nth-last-child(-n+3) { 
    /*declarations*/ 
} 

fiddle法布里西奧示範磨砂

這個選擇最後的3個孩子的把戲只會選擇那些返回一個正數用於N表達式(-n + 3)的行,並且由於我們使用的是第n個最後一個孩子,所以它從最後一個到第一個計數,所以從底部開始的第一行給出

f(n) = -n+3 
f(1) = -1+3 = 2 <- first row from the bottom 
f(2) = -2+3 = 1 <- second row from the bottom 
f(3) = -3+3 = 0 <- third row from the bottom 

一切將返回一個負數

+2

打我一分鐘:P [小提琴](http://jsfiddle.net/6BV3K/)爲您的答案 –

+0

一個-n這當然會maken 3,2,1,0,-1 ENZ,所以只選擇最後3個 – Ivo

5

這是可能的CSS3選擇器和formulas

.something a:nth-last-child(-n+3) { ... } 

您也可以嘗試using jQuery (example)或將特定類添加到服務器端代碼中的最後三個元素(它不需要在瀏覽器中啓用JavaScript,也可以在不支持CSS3的舊瀏覽器中使用)。