CSS 伪类选择器
本文将用代码例子的形式展示以下几个比较容易混淆的 css 伪类选择器的使用:
- p:first-of-type 选择属于其父元素的首个元素
- p:last-of-type 选择属于其父元素的最后元素
- p:only-of-type 选择属于其父元素唯一的元素
- p:only-child 选择属于其父元素的唯一子元素
- p:nth-type-of(n) 选择属于其父元素的第 n 个 p 元素
- p:nth-child(n) 选择属于其父元素的第 n 个子元素
点击这里查看本文提到的例子.
使用到的 html 片段如下:
1 | <body> |
first-of-type
1 | p:first-of-type { |
结果如下,p:first-of-type 选择属于其父元素的首个 p 元素。这里有 2 个 p 元素分别在各自的 div 父元素内部位于第一个,所以选择器选中了两个。
last-of-type
1 | p:last-of-type { |
last-of-type 和 first-of-type 对应,选择属于其父元素的最后一个 p 元素
only-of-type
1 | h3:only-of-type { |
x:only-of-type 选择属于其父元素唯一的 x 类型元素, 可以和下面的 only-child 对比,区别在于 only-child 限制更加强,必须是唯一子元素。
only-child
1 | h3:only-child { |
only-child 限制更加强,必须是唯一子元素。可以看到由于第一个 div 里不止一个 p 元素,所以没有 p 元素被选中,同样因为 h3 也不是第一个 div 里唯一的子元素,所以也没有被选中。
nth-type-of(n)
1 | p:nth-of-type(2n + 1) { |
可以看到 nth-type-of 选择器会忽略非选择的 type,比如这里的 h3,然后只对 p 做排序,选中奇数序列的元素
nth-child(n)
1 | p:nth-of-type(2n + 1) { |
和上面的 nth-type-of 相比, nth-child 不作元素类型的区别,只要是子元素都计入排序。