nth选择器详解
先來認識幾個常用的
- :first-child選擇某個元素的第一個子元素
- :last-child選擇某個元素的最后一個子元素
- :nth-child()選擇某個元素的一個或多個特定的子元素
- :nth-last-child()選擇某個元素的一個或多個特定的子元素,從這個元素的最后一個子元素開始算
- :nth-of-type()選擇指定的元素
- :nth-last-of-type()選擇指定的元素,從元素的最后一個開始計算
- :first-of-type選擇一個上級元素下的第一個同類子元素
- :last-of-type選擇一個上級元素的最后一個同類子元素
實例
基礎代碼:
<title>nth選擇器</title><style>.box1 p{background-color: red;margin-top: 20px;}</style> </head> <body><div class="box1"><p>111</p><p>222</p><p>333</p><p>444</p><p>555</p></div> </body> </html>
以下前兩個示例都是基于這個html
1. :first-child
代碼:
.box1 p:first-child{background-color: blue; }結果:
last-child與它相反,選擇的是最后一個
2. :nth-child()
代碼:
.box1 p:nth-child(2){background-color: blue; }結果:
代碼:
結果:
nth-last-child()與它相反,從最后一個開始算起
3. :nth-of-type()
下面的示例都是基于這個html
代碼:
<style>.box1 p{background-color: red;margin-top: 20px;}.box1 h1:nth-of-type(2n + 1){background-color: blue;}</style> </head> <body><div class="box1"><h1>h111</h1><h1>h222</h1><h1>h333</h1><p>111</p><p>222</p><p>333</p><p>444</p><p>555</p></div> </body> </html>結果:
代碼:
結果:
:nth-last-of-type()從最后一個算起
4. :first-of-type
代碼:
.box1 h1:first-of-type{background-color: blue; }結果:
代碼:
結果:
:last-of-type選擇最后一個
總結
- 上一篇: CentOS7中命令 ip addr 不
- 下一篇: python基础教程 学习前的准备