:first-child和:last-child可分别选中父容器中首个和末个li元素以设置样式,需确保li是首尾子元素,否则应改用:first-of-type/:last-of-type;二者兼容IE9+及以上。

可以通过 :first-child 和 :last-child 伪类分别选中列表中第一个和最后一个 <li> 元素,从而独立设置它们的样式。
基础用法:直接作用于 li 元素
确保目标元素确实是其父容器的第一个或最后一个子元素。常见写法如下:
-
ul li:first-child { border-top: 2px solid #333; }—— 给首个列表项加顶部边框 -
ul li:last-child { border-bottom: 2px solid #333; }—— 给末项加底部边框 - 若想首尾都圆角,可写:
ul li:first-child { border-radius: 4px 4px 0 0; },ul li:last-child { border-radius: 0 0 4px 4px; }
注意父子结构是否匹配
如果 <ul></ul> 内部有其他类型子元素(比如注释、空格文本节点不影响,但 <div> 或 <code><p></p> 会影响),:first-child 可能不生效。此时建议:
- 保持结构干净:只放
<li>在<ul></ul>内 - 改用
:first-of-type和:last-of-type更稳妥,它们按元素类型计算而非位置 - 例如:
ul li:first-of-type会选中第一个<li>,即使前面有<div> <h3>配合其他伪类增强控制力</h3> <p>可以组合使用实现更精细效果:</p><div class="aritcle_card flexRow"> <div class="artcardd flexRow"> <a class="aritcle_card_img" href="/xiazai/skill11815" title="CDP浏览器大师"><img src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="CDP浏览器大师" ></a> <div class="aritcle_card_info flexColumn"> <a href="/xiazai/skill11815" title="CDP浏览器大师">CDP浏览器大师</a> <p>CDP浏览器大师:通过Chrome DevTools Protocol驱动已登录浏览器实现自动化任务,解决反爬封号、选择器失效、SPA路由难导航、固定sleep不准四大痛点。核心能力包括UA伪装、WebGL/Canvas指纹混淆、智能等待、动态选择器以及可视化调试。</p> </div> <a href="/xiazai/skill11815" title="CDP浏览器大师" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p> <ul> <li> <code>ul li:first-child:not(:last-child) { margin-top: 10px; }—— 首项且非末项时加顶外边距 -
ul li:last-child:first-child { background: #eee; }—— 当列表仅一项时,同时满足首尾条件,可单独设样式 - 配合
:hover做交互:ul li:first-child:hover { transform: scale(1.05); }
兼容性与现代替代方案
:first-child 和 :last-child 在所有现代浏览器及 IE9+ 中均支持。如需兼容更老版本 IE,可用 JavaScript 补充;但当前项目基本无需考虑。
CSS 新增的 :has()(如 ul:has(> li:first-child))暂不适用于此场景,目前仍以 :first-child / :last-child 为主流可靠方案。

















