有什么区别:第一
我无法分辨出element:first-child
和element:first-of-type
之间的区别
比如说,你有一个div
div:first-child
→所有<div>
元素是其父项的第一个子项。
div:first-of-type
→所有<div>
元素是其父元素的第一个<div>
元素。
这似乎是完全一样的东西,但它们的工作方式不同。
有人能解释一下吗?
父元素可以有一个或多个子元素:
<div class="parent">
<div>Child</div>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
在这些孩子中,只有他们中的一个可以成为第一个。 这匹配:first-child
:
<div class="parent">
<div>Child</div> <!-- :first-child -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
:first-child
和:first-of-type
之间的区别在于:first-child
:first-of-type
将匹配其元素类型的第一个元素,即HTML中的第一个元素由其标记名称表示,即使该元素不是第一个元素父母的孩子。 到目前为止,我们所看到的儿童元素都是div
,但是忍耐着我,我会做到这一点。
现在,反过来也是如此:任何:first-child
也是:first-of-type
是必要的。 由于这里的第一个孩子也是第一个div
,它将匹配两个伪类以及类型选择器div
:
<div class="parent">
<div>Child</div> <!-- div:first-child, div:first-of-type -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
现在,如果您将第一个孩子的类型从div
更改为其他类型,比如h1
,它仍然是第一个孩子,但它不会再是第一个div
; 相反,它成为第一个(也是唯一的) h1
。 如果在同一个父级中的第一个子级之后还有其他div
元素,那么这些div
元素中的第一个将匹配div:first-of-type
。 在给定的例子中,第二个孩子成为第一个孩子变成h1
后的第一个div
:
<div class="parent">
<h1>Child</h1> <!-- h1:first-child, h1:first-of-type -->
<div>Child</div> <!-- div:nth-child(2), div:first-of-type -->
<div>Child</div>
<div>Child</div>
</div>
请注意:first-child
相当于:nth-child(1)
。
这也意味着,虽然任何元素可能只有一个子元素匹配:first-child
个子元素,但它可以并且将有多少个孩子匹配:first-of-type
伪类作为子类型的数量具有。 在我们的例子中,选择器.parent > :first-of-type
(带有隐式*
限定:first-of-type
伪)将匹配两个元素,而不仅仅是一个:
<div class="parent">
<h1>Child</h1> <!-- .parent > :first-of-type -->
<div>Child</div> <!-- .parent > :first-of-type -->
<div>Child</div>
<div>Child</div>
</div>
对于:last-child
和:last-of-type
:any :last-child
也是必须的:last-of-type
,因为其父元素中绝对没有其他元素。 然而,由于最后一个div
也是最后一个孩子,尽管h1
是最后一个孩子,但它不能是最后一个孩子。
我已经创建了一个示例来展示这里的first-child
和first-of-type
first-child
之间的区别。
HTML
<div class="parent">
<p>Child</p>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
CSS
.parent :first-child {
color: red;
}
.parent :first-of-type {
background: yellow;
}
.parent p:first-child {
text-decoration: line-through;
}
// Does not work
.parent div:first-child {
font-size: 20px;
}
// Use this instead
.parent div:first-of-type {
text-decoration: underline;
}
// This is second child regardless of its type
.parent div:nth-child(2) {
border: 1px black solid;
}
要查看完整示例,请访问https://jsfiddle.net/bwLvyf3k/1/
链接地址: http://www.djcxy.com/p/22859.html上一篇: What is the difference between :first
下一篇: child() or :nth