使用 :last-child 伪类可去除列表最后一项边框,如 ul li:last-child { border-bottom: none; },但需确保 li 是父元素最后一个同级子元素,否则可用 :nth-last-child(1) 或 :not(:first-child) 替代。
直接用 :last-child 伪类给列表最后一项设置 border: none 即可去除边框,前提是边框原本是通过父元素或每个 li 统一加的。
假设你用的是上下边框或底部边框:
ul li {
border-bottom: 1px solid #ccc;
}
ul li:last-child {
border-bottom: none;
}
:last-child 匹配的是其父元素中**最后一个同级子元素**。常见踩坑点:
ul 里除了 li 还有其他元素(比如注释、空格文本节点不影响,但 或 > 标签会),li:last-child 可能不生效
- 如果列表项是用
flex 或 grid 布局,且设置了 flex-wrap,仍以 DOM 顺序为准,不是视觉最后一行
- 想按“最后显示的一项”去边框?
:last-child 不管换行,只看 HTML 结构顺序
更稳妥的替代方案
如果结构复杂,或需要兼容老浏览器,可用 :nth-last-child(1),效果和 :last-child 一样,但语义更明确:
ul li:nth-last-child(1) {
border-bottom: none;
}
或者用 :not(:first-child) 反向思路——给除第一项外的所有项加顶边框,自然最后一项没多余边框:
ul li:not(:first-child) {
border-top: 1px solid #ccc;
}
如果是左右边框,去掉最后一项的右边界
例如横向菜单:
nav li {
border-right: 1px solid #999;
}
nav li:last-child {
border-right: none;
}
只要确保选择器命中目标 li,:last-child 就是最简洁可靠的方式。