CSS3 特殊但常用的選取器
:nth-child(n) vs :nth-of-type(n)
版本 | 選取器 | 舉 例 | 說 明 |
---|---|---|---|
2 | :first-child | p:first-child | 符合左側指定的元素, 並且是所屬層次中的第一個子元素。
參考【英文版】 【簡中版】 |
3 | :first-of-type | p:first-of-type | 在所屬層次中符合左側指定元素的第一個元素。
參考【英文版】 【簡中版】 |
3 | :last-child | p:last-child | 符合左側指定的元素, 並且是所屬層次中的最後一個子元素。
參考【英文版】 【簡中版】 |
3 | :last-of-type | p:last-of-type | 在所屬層次中符合左側指定元素的最後一個元素。
參考【英文版】 【簡中版】 |
3 | :only-child | p:only-child | 符合左側指定的元素, 並且是所屬層次中的唯一子元素。
參考【英文版】 【簡中版】 |
3 | :only-of-type | p:only-of-type | 在所屬層次中符合指定元素p, 並且只有一個指定元素p。
參考【英文版】 【簡中版】 |
3 | :nth-child(n) | p:nth-child(n) | 符合左側指定的元素, 並且是所屬層次中符合第 n 個子元素。
參考【英文版】 【簡中版】 |
3 | :nth-of-type(n) | p:nth-of-type(n) | 在所屬層次中符合第 n 個指定元素 p。
參考【英文版】 【簡中版】 |
3 | :nth-last-child(n) | p:nth-last-child(n) | 符合左側指定的元素, 並且是所屬層次中符合倒數第 n 個子元素。
參考【英文版】 【簡中版】 |
3 | :nth-last-of-type(n) | p:nth-last-of-type(n) | 在所屬層次中符合倒數第 n 個指定元素 p。
參考【英文版】 【簡中版】 |
3 | :not(選取器) | :not(p) | 排除指定標籤之外的符合元素為選取器。
參考【英文版】 【簡中版】 |
HTML 部份
<h2 style="text-align:center;">測試:nth-child與:nth-of-type</h2> <p>1111111111</p> <p class="abc">2222222222</p> <p class="abc">3333333333</p> <p>4444444444</p> <p>5555555555</p> <p>6666666666</p> <div>777777777777</div> <div class="abc">777777777777</div> <div> <p>1111111111</p> <p>2222222222</p> <p class="abc">3333333333</p> <p>4444444444</p> <p>5555555555</p> <p>6666666666</p> </div> <div class="abc">777777777777</div> <style> #b1 { border: 2px solid #666; padding: 10px; } #b1 div { background-color: #b4e2ff; padding: 5px; margin: 10px; } </style>
測試相關 -child 與 -of-type
<h2>測試相關 -child 與 -of-type
<p>1111111111
<p class="abc">2222222222
<p class="abc">3333333333
<p>4444444444
<p>5555555555
<p>6666666666
<div>777777777777
<div class="abc">777777777777
<p>1111111111
<p>2222222222
<p class="abc">3333333333
<p>4444444444
<p>5555555555
<p>6666666666
<div class="abc">777777777777