css中first-of-type和first-child 的区别
first-of-type
mdn中的释义::first-child CSS 伪类表示在一组兄弟元素中的第一个元素。
first-child
mdn中的释义:CSS 伪类 :first-of-type 表示一组兄弟元素中其类型的第一个元素。
我自己的解释是:first-child 说的是匹配同组兄弟元素的第一个,但当匹配的元素与第一个元素不符合时,这时匹配不生效,说明first-child匹配的元素必须要是子元素的第一个也要是同类型元素。 first-of-type 则说的是匹配一组兄弟元素中其类型的第一个元素,说明只要类型匹配成功不管是不是元素组中的第一个。都能成功
直接看代码:
<style>
* {
margin: 0;
padding: 0;
}
ul li:first-child {
color: red;
}
ul li:first-child {
font-weight: bold;
}
ul p:first-of-type {
color: green;
}
ul p:first-of-type {
background-color: pink;
}
</style>
</head>
<body>
<ul>
<!-- <li>444</li> -->
<div>333</div>
<li>234</li>
<li>234</li>
<p>123</p>
<p>123</p>
<span>345</span
><br />
<span>345</span>
</ul>
</body>
当first-child匹配的元素不是第一个时,而first-of-type 匹配的元素也不是第一个时结果是
<body>
<ul>
<<li>444</li>
<div>333</div>
<li>234</li>
<li>234</li>
<p>123</p>
<p>123</p>
<span>345</span
><br />
<span>345</span>
</ul>
</body>
当first-child匹配的元素是第一个时,而first-of-type 匹配的元素也不是第一个时结果是
ul li:first-of-type {
background-color: yellow;
}
当first-child匹配的元素是第一个时,而first-of-type 匹配的元素也是第一个时结果是
当我把ul的数量加倍时而样式不变时结果是这样的(第一个ul中去掉了第一个位的div)
PS:以上纯属个人经验,如有错误欢迎指教