结构伪类选择器 nth-child

233 阅读2分钟

结构伪类 nth-child

根据结构来选择标签,选儿子(亲儿子) 选择第几个,比如选择第4、8个元素等,这是结构伪类的使用场景。

但是,结构伪类nth-child使用,是有具体要求的, 如果非要按按照顺序来使用,必须是亲兄弟。

比如:这个排序比较简单

<ul>
    <li>手机</li>
    <li>电脑</li>
    <li>榴莲</li>
</ul>
选择第3li
ul li:nth-child(3) {
    color: red;
}

但是,如果是这样,则排序就不对:

<div class="box">
     <a href="#">链接</a>
     <p>我是段落</p>
     <p>我是段落</p>
     <p>我是段落</p>
     <p>我是段落</p>
</div>

nth-child() 选孩子的时候,不一定是同类的, 依次来排号。

进行选择的时候,先执行 nth-child(n) 先按照序号找到这个元素, 然后再看前面的标签选择器能否匹配。

.box p:nth-child(3) {
    color: red;
}

nth-child(n)

假设ul里面包含8个li标签

  1. n 可以是数字, 数字是几,就选择第几个孩子。

    ul li:nth-child(6) { }  选择第6个孩子
    
  2. n 还可以是 关键字 比如 odd even

/* 关键词  even 偶数  odd 奇数*/ul li:nth-child(even) {
    background-color: skyblue;
}
​
ul li:nth-child(odd) {
    background-color: pink;
}

注意:

  1. nth-child(1) === first-child {}
  2. nth-child(8) === last-child {}
  3. nth-child 不能完全替代 first和 last-child 因为很多情况下,我们不知道有多少个孩子。
  1. n 还可以是 公式。

    • n 是从 0开始 012345...
    • 2n 是 偶数
    • 2n + 1 是 奇数
    • -n+3 选择前面3个
    • n+3 从第3个(包含第三个)往后面选
/* 3. 公式  n 默认从 0开始  0123456*/
/* ul li:nth-child(2n) {
background-color: pink;
} */
/* ul li:nth-child(-n+3) {
background-color: pink;
} */ul li:nth-child(n+3) {
    background-color: pink;
}

另外一个选择器nth-of-type() 选择的时候可以分类, 必须是同一类

p:nth-of-type(1)

执行顺序: 先看 p, 再执行 nth-of-type 从1开始排号。

基础提问咯

请问下面结构中,如果把榴莲的颜色改为红色:

<ul>
    <li><a href="#">手机</a></li>
    <li><a href="#">电脑</a></li>
    <li><a href="#">榴莲</a></li>
</ul>

答案:

ul li:nth-child(3) a {
   color: red;
}