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

使用CSS列表计数器实现父子列表不同编号样式出错求助

错误原因

  1. counters函数参数顺序错误:counters()的正确语法为counters(计数器名, 分隔符, [计数样式]),你把大写罗马样式upper-roman放在了第二个参数(分隔符)的位置,语法解析错误后样式回退为默认十进制,这是最核心的问题。
  2. 选择器匹配范围冲突:.sample ol > li:before会匹配所有层级ol的直接子li,包括二级列表的li,会和二级列表的样式规则产生优先级冲突。
  3. 多规则冗余冲突:你同时定义了ul和ol的共用counter规则,后续又单独覆盖ol的样式,冗余的规则进一步增加了冲突概率。

修正后的CSS代码

/* ol单独定义避免和ul规则冲突 */
.sample ol {
    margin-left: 0;
    padding-right: 0;
    list-style-type: none;
    counter-reset: step-counter;
}
.sample ol > li {
    counter-increment: step-counter;
    position: relative; 
    padding-left: 27px;
    margin-bottom: 30px;
}
/* 明确匹配第一级ol的li */
.sample > ol > li:before {
    content: counter(step-counter, decimal);
    position: absolute;
    left: 0;
}
/* 二级ol的li样式,不需要拼接父级编号直接用counter即可 */
.sample ol ol > li:before {
    content: counter(step-counter, upper-roman) ".";
}

/* 以下是原ul的规则可保留,不影响ol效果
.sample ul {
    margin-left: 0;
    padding-right: 0;
    list-style-type: none;
    counter-reset: step-counter;
}
.sample ul > li {
    counter-increment: step-counter;
    position: relative; 
    padding-left: 27px;
    margin-bottom: 30px;
}
.sample ul > li:before {
    content: counter(step-counter, disc);
    position: absolute;
    left: 0;
    font-size: 24px;
    line-height: 24px;
}
*/

如果需要拼接父级编号显示为1.I、1.II这类格式,可以用正确的counters写法:

.sample ol ol > li:before {
    content: counters(step-counter, ".", upper-roman) ".";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:54:03