十几个例子重温CSS易混淆的选择器

126 阅读3分钟

我正在参加「掘金·启航计划」

文章示例基本来自于 css dinner 和 CSS Speedrun。文中所有知识点在 MDN 都可以找到。自己在解题的时候发现每个示例有一种或多种写法,可以运用不同的选择器或者伪类来找到元素,而且好记性不如烂笔头,特此记录下来。

1. 选择一个直接跟在另一个元素后面的元素

image.png

解答:箭头所指的 apple元素的特点是都直接跟在 plate元素后面

  • plate + apple

2. 选择一个元素后面的所有具体某个类型的元素

image.png

解答:span的特点是都在 p元素后面,不过需要注意的是箭头所指的第三个span不是直接跟在p元素后面

  • p ~ span

3. 选择元素的直接后代元素

image.png

解答:箭头所指的apple元素是plate的直接后代元素,和第三行的apple不同的是,第三行的apple元素是plate的子元素,而不是直接后代元素,但他是bento的直接后代元素。

  • plate > apple

4. 在一个元素里面选择第一个子元素

image.png

解答:orange元素是其父元素的第一个子元素

  • plate orange:first-child()
  • plate orange:nth-child(1)
  • plate orange:nth-last-child(3)
  • plate orange:first-of-type
  • plate orange:nth-of-type(1)

5. 选择一个元素,这个元素是其父元素中唯一的元素

image.png

解答:

  • plate *:only-child
  • plate :only-child (中间有空格)

6. 在一个元素里面选择最后一个子元素

image.png

解答:

  • .small:last-child
  • 匹配最后一个apple和最后一个pickle:apple:last-child,pickle:last-child
  • 匹配除了orange外的所有的最后一个元素::last-child:not(orange)

7. 在一个元素里面按照次序选择其子元素

image.png

解答:

  • plate:nth-child(3)

需要注意的是: nth-child(3) 匹配 plate 的父元素下的第 3 个 plate 元素,当 plate 的父元素的第 3 个子元素不是 plate ,则不进行匹配。

8. 在一个元素里面按照特定次序选择其子元素,从后面数起

image.png

解答:

  • bento:nth-child(2)
  • bento:nth-last-child(3)

9. 选择特定类型的第一个元素

image.png

解答:

  • apple:nth-of-type(1)
  • apple:first-of-type
  • apple:nth-child(2)

10. 在一个元素里面按照特定次序和特定类型选择其子元素

image.png

解答:

  • plate:nth-of-type(2n)
  • plate:nth-of-type(even)
  • 因为上面plate的父元素只有plate一种子元素,所以也可以用: plate:nth-child(2n)

11. 选择在其父元素中唯一属于其类型的元素

image.png

解答:

  • 需要匹配的元素是其父元素的唯一子元素:plate apple:only-child
  • 需要匹配的元素是其父元素的所有子元素中唯一类型的元素:plate apple:only-of-type
  • 下面的例子中,就可以用 only-of-type 匹配第一个 ul里面的 li
<div>
  <ul class="first">
    <li></li>
    <p></p>
  </ul>
  <ul class="second">
    <li></li>
    <li></li>
  </ul>
</div>

12. 在一个元素里面选择特定类型的最后一个子元素

image.png

解答:

  • orange:last-of-type,apple:last-of-type
  • .small:last-of-type"

13. 选择没有子元素的元素

image.png

解答:

  • bento:empty

14. 选择所有不匹配否定选择器的元素

image.png

解答:我觉得否定选择器挺有用的,可以搭配其他选择器使用。

  • 直接用否定选择器:apple:not(.small)
  • 也可以这样搭配:apple:last-of-type:not(.small)