如下代码块是一个html结构,接下来将会使用first-child和first-of-type分别进行css操作,从而找出他们的区别。
<div id="example">
<p>1</p>
<div>2</div>
<div>3</div>
</div>
1、first-child
#example>div:first-child {
background-color: pink;
}
first-child没有选择出任何元素,因为他的工作步骤是这样的:
① 把所有#example的children排成一列
② 找到第一个child
③ 第一个child为div则选出
由于第一个child不为div,则查找失败,没有产生css效果
2、first-of-type
#exzmple>div:first-of-type {
background-color: pink;
}
first-of-type选择出了内容为2的div,原因如下:
① 把所有#example中的children中的div排成一列
② 找到第一个child
此例第一个div选择出来,并把background-color改成了pink颜色
本文通过实例对比了CSS中first-child与first-of-type选择器的区别。first-child仅选择作为其父元素的第一个子元素,而first-of-type则选择其父元素中特定类型的第一个子元素。深入解析两者的工作原理及应用场合。
1161

被折叠的 条评论
为什么被折叠?



