:first-child 和 :last-child 是基于子元素位置选择第一个或最后一个子项的伪类,用于精准控制列表、导航等布局的首尾样式。

:first-child 和 :last-child 是 CSS 中的伪类选择器,用于选中父元素下的第一个或最后一个子元素。它们在实际开发中非常实用,比如用于调整列表、导航栏或卡片布局的样式。
p:first-child 会选中作为第一个子元素的 <p></p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/804">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175679969542307.jpg" alt="零一万物开放平台">
</a>
<div class="aritcle_card_info">
<a href="/ai/804">零一万物开放平台</a>
<p>零一万物大模型开放平台</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="零一万物开放平台">
<span>48</span>
</div>
</div>
<a href="/ai/804" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="零一万物开放平台">
</a>
</div>
标签。
<li>
li:first-child 常用于去除列表第一项的上边距或添加特殊样式。
li:first-child {
color: red;
margin-top: 0;
}
<li> 文字变红,并重置其上边距。
:first-child 类似,:last-child 匹配父元素下的最后一个子元素。
常用于处理排版间距,比如去掉最后一项的下边距。
示例:
p:last-child {
margin-bottom: 0;
}
div span:first-child 不表示“选中 div 内的第一个 span”,而是“选中 div 内既是第一个子元素又是 span 的元素”。
<li>若想选中某类型元素的第一个或最后一个,应使用 :first-of-type 或 :last-of-type。
.menu li:first-child {
border-radius: 8px 0 0 8px;
}
.menu li:last-child {
border-radius: 0 8px 8px 0;
}
基本上就这些。掌握 :first-child 和 :last-child 能让你更灵活地控制结构样式,关键是理解它们基于“位置”而非“类型”。
以上就是css选择器:first-child与:last-child如何使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号