close


支援CSS3 以上

用法: :nth-last-child(n)
說明:
n 為第幾個子元素,
依tag為第幾個子元素套用樣式

此nth-last-child為:子元素從後開始算

css定義:
從後算來第2個子元素且是a tag
a:nth-last-child(2){
font-size: 20px;
color: silver;
}
從後算來第4個子元素且是p tag
p:nth-last-child(4){
font-size: 20px;
color: red;
}
注意事項:
只算第幾個子元素,不分tag。
只要有父子關系,都會被定義。

有分tag


程式:
<!DOCTYPE html>
<html>
<head>
<title>css3 Selector nth-last-child(n) 套用樣式</title>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<style type="text/css">
a:nth-last-child(2){
font-size: 20px;
color: silver;
}

p:nth-last-child(4){
font-size: 20px;
color: red;
}
</style>
</head>
<body>
<a href="#1">a tag test 1</a>
<a href="#2">a tag test 2</a>
<a href="#3">a tag test 3</a>
<p>p tag test 1</p>
<a href="#4">a tag test 4</a>
<p>p tag test 2</p>

<div>
<a href="#1">div a tag test 1</a>
<a href="#2">div a tag test 2</a>
<a href="#3">div a tag test 3</a>
<p>div p tag test 1</p>
<a href="#4">div a tag test 4</a>
<p>div p tag test 2</p>
</div>
</body>
</html>

例說明:
a:nth-last-child(2) 從後算第2個子元素為a tag 則套用
p:nth-last-child(4) 從後算第4個子元素為p tag 則套用

父元素為body ,子元素順序為:

前數            後數檢查元素   是否套用
1、a tag 1 |7、a tag 1 | |
2、a tag 2 |6、a tag 2 | |
3、a tag 3 |5、a tag 3 | |
4、p tag 1 |4、p tag 1 |檢查為p tag |是套用
5、a tag 4 |3、a tag 4 | |
6、p tag 2 |2、p tag 2 |檢查為a tag |否套用
7、div tag |1、div tag | |


父元素為div ,子元素順序為:
前數              後數檢查元素  是否套用
1、div a tag 1 |6、div a tag 1 | |
2、div a tag 2 |5、div a tag 2 | |
3、div a tag 3 |4、div a tag 3 |檢查為p tag |否套用
4、div p tag 1 |3、div p tag 1 | |
5、div a tag 4 |2、div a tag 4 |檢查為a tag |是套用
6、div p tag 2 |1、div p tag 2 | |



圖1:






測試結束~
如果還不了解可參考:w3schools CSS Selector Reference


感謝~




 






 
















其它文章

arrow
arrow

    PG Levin Li 發表在 痞客邦 留言(0) 人氣()