CSS 伪类选择器 :last-child 表示包含元素内的最后一个元素。
伪类 :last-child 类似于 :last-of-type,但前者更具体,针对父元素的最后一个子元素,而后者匹配指定元素的最后一次出现。
语法
:last-child {
/* ... */
}
CSS :last-child 示例
以下示例演示了 :last-child 伪类的用法。在此示例中,CSS 规则仅适用于在 <div> 元素中找到的最后一个 <p> 元素,而同一容器中的其他 <p> 元素不受影响。
<html>
<head>
<style>
p:last-child {
color: black;
background: yellow;
font-weight: 600;
font-size: 1em;
font-style: italic;
padding: 5px;
}
div {
border: 2px solid black;
margin-bottom: 5px;
}
</style>
</head>
<body>
<div>Parent element
<p>first child, so no change</p>
<p>second/last child, so :last-child pseudo-class applied</p>
</div>
<div>Parent element
<h2>h3 tag, so no change</h2>
<p><p> tag, is the last child.</p>
</div>
</body>
</html>
以下示例演示了在 <li> 标记的父元素下的 <ul> 下如何使用 :last-child 伪类。在此示例中,CSS 规则仅适用于在 <ul> 元素中找到的最后一个 <li> 元素,而同一容器中的其他 <li> 元素不受影响。
<html>
<head>
<style>
ul li:last-child {
color: black;
background: peachpuff;
font-weight: 600;
font-size: 1em;
font-style: italic;
padding: 5px;
}
div {
border: 2px solid black;
margin-bottom: 5px;
width: 300px;
}
</style>
</head>
<body>
<div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three
</ul>
</div>
</body>
</html>