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

CSS中给有序列表应用nth-child(odd)时背景未占满整行如何解决?

问题核心原因

你给li设置的margin-left: 40px是导致背景无法覆盖整行的核心原因:CSS中元素的margin区域默认透明,不会被自身的background属性渲染,左侧未被背景覆盖的空白就是li的margin区域。

解决方案

  • 方案1:调整缩进实现逻辑,保持序号在背景外的原有布局
    将原来li的左margin转移到父级ol的padding上,既保留原有缩进效果,又能让li的背景覆盖整行:
/* 父级有序列表样式 */
ol {
  padding-left: 40px;
  margin: 0;
}

li{
  font-family: serif;
  font-size: 20px; 
  position: relative;
  padding: 20px 0px 10px 20px;
  /* 移除原有的margin-left: 40px */
}

li:nth-child(odd){
  background-color: violet;
}
  • 方案2:序号放入li内容区域,背景覆盖含序号的整行
    给ol设置list-style-position: inside让序号在li盒子内部渲染,背景会覆盖包含序号的整行区域:
ol {
  padding-left: 0;
  margin: 0;
  list-style-position: inside;
}

li{
  font-family: serif;
  font-size: 20px; 
  position: relative;
  padding: 20px 0px 10px 20px;
  margin-left: 0;
}

li:nth-child(odd){
  background-color: violet;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:06:03