假设我们有以下 HTML:
<div>
<h1>First h1</h1>
<h1>Second h1</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
如果我们想定位 div 的最后一个子元素,我们将使用:
div :last-child {
color: red;
}
/*note the white space between div and :last-child*/
如果我们只想定位 div 的最后一个子元素(仅当该子元素是一个p元素时),那么我们将拥有:
div p:last-child {
color: red;
}
另一方面,last-of-type将定位该类型元素的最后一次出现。因此,假设我们要定位h1div 中最后一次出现的元素:
div h1:last-of-type {
color: blue;
}
不一定last-of-type是最后一个孩子。
这些选择器还有许多补充替代方案,例如 : 、:first-of-type等。:nth-last-of-typefirst-child