:last-of-type
选择器用于选择同类型元素中的最后一个。它的对立面是:first-of-type
选择器,这个选择器用于选择同类型元素中的第一个。
:first-of-type
: 选择同类型元素中的第一个。:last-of-type
: 选择同类型元素中的最后一个。:first-of-type
::last-of-type
::first-of-type
::last-of-type
:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
p:first-of-type {
color: blue;
font-weight: bold;
}
p:last-of-type {
color: green;
text-decoration: underline;
}
</style>
</head>
<body>
<div>
<p>这是第一个段落。</p>
<span>这是一个span元素。</span>
<p>这是第二个段落。</p>
<div>这是一个div元素。</div>
<p>这是最后一个段落。</p>
</div>
</body>
</html>
在这个例子中,第一个段落将以蓝色加粗显示,而最后一个段落将以绿色并带有下划线显示。
如果你在使用:first-of-type
或:last-of-type
时遇到问题,比如选择器没有按预期工作,可能的原因包括:
通过仔细检查CSS规则、HTML结构和浏览器兼容性,通常可以解决这类问题。
领取专属 10元无门槛券
手把手带您无忧上云