结构伪类选择器

结构伪类选择器,可以根据元素在文档中所处的位置,动态地选择元素,从而减少HTML文档对ID或类的依赖,有助于保持代码干净整洁。 结构伪类选择器的权重为0,0,1,0

选择符 简介
E:first-child 匹配父元素中的第一个子元素E
E:last-child 匹配父元素中最后一个E元素
E:nth-child(n) 匹配父元素中的第n个子元素E
E:first-of-type 指定元素E的第一个
E:last-of-type 指定元素E的最后一个
E:nth-of-type(n) 指定元素E的第n个
E:only-child 匹配的元素的父元素中仅有一个子元素,而且是一个唯一的子元素
E:only-of-type 用来选择一个元素,它是父元素唯一一个相同类型的子元素。
:nth-last-child 从最后一个子元素开始计数

注意: 结构伪类始终依附在要选择的那个元素上 ,而不是父元素。

示例

有如下页面结构:

  1. <ul>
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. <li>4</li>
  6. <li>5</li>
  7. <li>6</li>
  8. <li>7</li>
  9. <li>8</li>
  10. <li>9</li>
  11. <li>10</li>
  12. </ul>

E:first-child 和 E:last-child

/*选择ul元素里面的第1个li元素*/
ul li:first-child {
            background-color: skyblue;
}
/*选择ul元素里面的最后一个li元素*/
ul li:last-child {
            background-color: blue;
}
/*也可以这样写,注意空格*/
ul :first-child {
            background-color: skyblue;
}

nth-child(n)

nth-child(n)中 n 可以是数字、关键字、公式

  • n 如果是数字,就是选中父元素的第 n 个子元素。
  • 常见的关键字有 even 偶数、odd 奇数
  • 常见的公式如下:( n 是从 0 开始计数的,子元素序号是从 1 开始计数的。 因此,n=0 不会选中任何元素。)

nthchildcanshu.png

/*选择ul元素里面的第6个li元素*/
ul li:nth-child(6) {
            background-color: skyblue;
}
/*选择ul元素里面的序号为偶数li元素*/
ul li:nth-child(even) {
      background-color: skyblue;
}
/*选择ul元素里面的序号>=5的li元素*/
ul li:nth-child(5n) {
      background-color: skyblue;
}

E:first-of-type 和 E:last-of-type

xxx-child 选择父元素里面的某一个子元素,而不管元素类型。xxx-of-type可选择指定元素类型。
E:xxx-of-type 来说, E 特指“元素类型” 。

<div>
        <h1>我是标题</h1>
        <p>我是段落1</p>
        <p>我是段落2</p>
        <p>我是段落3</p>
</div>
/*选中第一个段落*/
div p:first-of-type {
            background-color: blue;
}
/*选中最后一个段落*/
 div p:last-of-type {
            background-color: blue;
}

值得注意:E:first-of-type 并不是选择整个HTML文档的第一个E元素,而是 选择含有E元素的父元素中的第一个E元素 (有点绕),结合后代选择器限定到父元素范围是一个很好的选择。

E:only-child 和 E:only-of-type

  1. E:only-child,匹配的元素的父元素中仅有一个子元素(也可以是唯一的后代),而且是一个唯一的子元素。

    <div class="post">
    <p>我是一个段落</p>
    <p>我是一个段落</p>
    </div>
    <div class="post">
    <p>我是一个段落</p>
    </div>
    
    .post p {
    background: green;
    color: #fff;
    padding: 10px;
    }
    .post p:only-child {
    background: orange;
    }
    

    上述样式中,只有HTML的最后一个段落的背景会被设置为橘黄色。

  2. E:only-of-type,用来选择一个元素,它是父元素唯一一个相同类型的子元素