默认序号由::marker伪元素生成,不可样式化;自定义徽章需禁用原生序号,用counter-reset/counter-increment配合li::before实现可控样式,兼容IE8+且支持背景、圆角等。

ol 默认序号和自定义徽章的区别在哪
浏览器渲染
时,序号是伪元素生成的(::marker),不占 DOM 节点,也不能直接加背景、边框或圆角。所谓“加徽章”,本质是**绕过默认序号,用 CSS 重绘一个带样式的序号容器**。别试图给 li::before 硬套 list-style: none 后再 position 定位——容易错位、响应式崩、打印失效。
用 counter-reset + counter-increment 实现可控徽章
这是最稳定的方式:禁用原生序号,用 CSS 计数器生成数字,再包裹进 li::before 里做样式。
li::before 里做样式。
关键步骤:
- 给
加counter-reset: item - 每个
li加counter-increment: item - 用
li::before的content: counter(item)显示数字 - 把
li::before设为display: inline-flex,就能自由加背景、圆角、内边距
ol {
counter-reset: item;
list-style: none;
padding-left: 0;
}
ol li {
counter-increment: item;
position: relative;
padding-left: 42px;
}
ol li::before {
content: counter(item);
display: inline-flex;
justify-content: center;
align-items: center;
position: absolute;
left: 0;
width: 28px;
height: 28px;
background: #007bff;
color: white;
border-radius: 50%;
font-size: 14px;
font-weight: 600;
}
注意 margin/padding 和垂直对齐的坑
li::before 是绝对定位,但它的基线仍受 li 行高影响。如果文字换行或字体大小不一,徽章容易上下偏移。
稳妥做法:
- 给
li设置固定line-height(比如1.5),并确保li::before的top或transform: translateY(-50%)配合top: 50%居中 - 避免在
li上设margin-top,改用padding-top控制项间距,防止徽章悬空 - 如果列表嵌套,记得给子
ol单独设counter-reset,否则会继承父级计数
需要支持 IE11?别用 ::marker
::marker 在 IE11 完全不支持,且不能设背景或 flex。哪怕只为了兼容性,也该坚持用 counter 方案——它从 IE8 就能跑。顺带一提,counter() 函数本身不支持字符串前缀(比如 “Step 1”),真要加文字得用 content: "Step " counter(item),但 IE11 不认这种写法,所以纯数字徽章是最安全的交集。
细节都在 counter-increment 的触发时机和 li::before 的盒模型控制里,多调两次 line-height 和 transform 就稳了。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











