:first-child、:first-of-type 与 :last-child、:last-of-type

:first-child 与 :last-child

:first-child 是一个伪类,如果它是某个其他元素的第一个子元素,则选择该元素。也就是说,:first-child 将匹配元素,只要它是它的父级的第一个子级。

举个例子吧:

我是第一个子级

我是第二个子级

接着我们再给它添加 CSS 吧:

div p:first-child {
  font-size: 24px;
}

结果如下:

:first-child、:first-of-type 与 :last-child、:last-of-type_第1张图片
first-child

很好理解吧,因为这个伪类只会匹配父级后面的第一个标签。

那么 :last-child 也就很好理解啦,匹配最后一个标签。

div p:last-child {
  font-size: 24px;
}

结果如下:

:first-child、:first-of-type 与 :last-child、:last-of-type_第2张图片
last-child

:first-of-type 与 :last-of-type

:first-of-type 是一个伪类选择器,它选择一个元素,该元素是其父类的子元素列表中其类型的第一个元素(兄弟元素)。

这个方法很好用的。我们还是拿例子来说吧:

我是第一个子级

我是第二个子级


我是第三个子级
我是第四个子级

如果使用这个伪类的话:

div span:first-of-type {
  font-size: 24px;
}

结果如下:

:first-child、:first-of-type 与 :last-child、:last-of-type_第3张图片
first-of-type

这样,就匹配了 div 后面的第一个标签 span

那么 :last-of-type 我就不用再说了吧。


总结

将这些东西真的很难,因为它很简单。。没有什么深奥的东西,如果这些知识讲的不好请见谅。

你可能感兴趣的:(:first-child、:first-of-type 与 :last-child、:last-of-type)