You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS问题:first-child、last-child和only-child伪类在列表中失效

解决CSS伪类样式不符合预期的问题

你当前的问题根源在于错误理解了伪类的作用对象:a:first-child/a:last-child/a:only-child 是判断 <a> 是否是它父元素(也就是 <li>)的对应子元素,但你的每个 <li> 里只有一个 <a>,所以所有 <a> 同时满足这三个伪类条件。又因为CSS规则优先级相同,后面的样式会覆盖前面的,最终所有 <a> 都应用了 a:only-child 的样式。

修正后的CSS代码

li {
  list-style: none;
}

a {
  padding: 10px;
  display: inline-block;
  background-color: green;
  color: yellow;
  text-decoration: none;
}

/* 每个div中ul的第一个li里的a设置红色背景 */
div ul li:first-child a {
  background-color: red;
}

/* 每个div中ul的最后一个li里的a设置蓝色背景 */
div ul li:last-child a {
  background-color: blue;
}

/* 仅最后一个div中ul的唯一li里的a设置灰色背景、圆角、白字 */
div ul li:only-child a {
  border-radius: 60%;
  background-color: grey;
  color: white;
}

说明

  • 通过基于 <li> 的伪类来选择对应的 <a>,精准匹配你需要的位置:
    • li:first-child 选中每个列表的第一个列表项,再选中里面的 <a> 实现红色背景
    • li:last-child 选中每个列表的最后一个列表项,再选中里面的 <a> 实现蓝色背景
    • li:only-child 选中仅包含一个列表项的列表里的 <li>,再选中里面的 <a> 实现灰色样式,刚好匹配最后一个div的情况

内容的提问来源于stack exchange,提问作者Edgar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:54:22