css选择器:first-child与:last-child如何使用

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

css选择器:first-child与:last-child如何使用

:first-child:last-child 是 CSS 中的伪类选择器,用于选中父元素下的第一个或最后一个子元素。它们在实际开发中非常实用,比如用于调整列表、导航栏或卡片布局的样式。

什么是 :first-child

这个伪类匹配其父元素下的第一个子元素,前提是该元素符合选择器指定的类型。 例如:
    <li> p:first-child 会选中作为第一个子元素的 <p></p> <div class="aritcle_card"> <a class="aritcle_card_img" href="/ai/1648"> <img src="https://img.php.cn/upload/ai_manual/000/969/633/68b6d7ce2ee2f805.png" alt="Content at Scale"> </a> <div class="aritcle_card_info"> <a href="/ai/1648">Content at Scale</a> <p>SEO长内容自动化创作平台</p> <div class=""> <img src="/static/images/card_xiazai.png" alt="Content at Scale"> <span>154</span> </div> </div> <a href="/ai/1648" class="aritcle_card_btn"> <span>查看详情</span> <img src="/static/images/cardxiayige-3.png" alt="Content at Scale"> </a> </div> 标签。 <li> li:first-child 常用于去除列表第一项的上边距或添加特殊样式。
示例:
  li:first-child {
    color: red;
    margin-top: 0;
  }
这段代码会让列表中的第一个 <li> 文字变红,并重置其上边距。

什么是 :last-child

:first-child 类似,:last-child 匹配父元素下的最后一个子元素。 常用于处理排版间距,比如去掉最后一项的下边距。 示例:
  p:last-child {
    margin-bottom: 0;
  }
如果一个容器最后一个子元素是段落,就会应用这条规则,避免多余空白。

使用注意事项

这两个选择器依赖于元素在父容器中的位置,而不是类型数量。例如:
    <li>如果第一个子元素不是目标标签,即使后面有匹配的标签,也不会被选中。 <li> div span:first-child 不表示“选中 div 内的第一个 span”,而是“选中 div 内既是第一个子元素又是 span 的元素”。 <li>若想选中某类型元素的第一个或最后一个,应使用 :first-of-type:last-of-type

常见应用场景

这些伪类在以下场景中特别有用:
    <li>导航菜单中高亮第一个或最后一个按钮。 <li>文章段落之间统一间距,仅对首尾段做特殊处理。 <li>图片列表中为第一张和最后一张添加圆角或阴影效果。
比如:
  .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如何使用的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。