伪元素列表序号应优先用::marker实现语义化美化,兼容性不足时用counter-reset+::before降级,复杂样式需改用li::before绝对定位实现。

用伪元素做列表序号,核心是语义正确 + 视觉可控 + 兼容稳妥。现代方案首选 ::marker,但不能只靠它;复杂样式或旧浏览器支持必须搭配 counter-reset 和 ::before 降级。
用 ::marker 快速美化数字颜色和字体
这是最轻量、最语义化的起点——只改序号本身的外观,不影响结构和可访问性:
-
ol li::marker只对原生<li>生效,且要求display: list-item(默认就是) - 能安全设置的属性只有:
color、font-size、font-weight、font-family、text-align(部分浏览器) - 例如让序号变蓝加粗:
ol li::marker { color: #2563eb; font-weight: bold; font-size: 1.1em; }
用 content + counter 自定义编号格式
::marker 的 content 属性允许你重写序号内容,但必须用 counter() 函数保持计数逻辑:
- 默认计数器名是
list-item,所以counter(list-item)就是当前数字 - 空格要手动加:想显示
[1],就得写content: "[" counter(list-item) "] "(末尾空格保留缩进) - 支持格式化:如
counter(list-item, decimal-leading-zero)输出001,lower-alpha输出a - 注意:
content: "Step " counter(list-item) ". "合法;content: "→ "则丢失编号,变成全一样
兼容旧浏览器:用 counter-reset + ::before 回退
Chrome 86+、Firefox 96+、Safari 15.4+ 支持 ::marker,但 iOS 16 或 IE 完全不识别。稳妥做法是双轨并行:
- 先给
<ol>设counter-reset: item;,再给li设counter-increment: item; - 然后用
li::before输出序号:ol li::before { content: counter(item) ". "; color: #2563eb; font-weight: bold; } - 同时加
ol li { list-style: none; }关闭原生序号,避免重复 - 这样即使
::marker被忽略,::before仍能兜底显示
做带背景或图标的序号?别硬套 ::marker
::marker 不支持 background、padding、border、transform,强行写会静默失效:
- 想要圆形色块包裹数字、图标+文字组合、悬浮效果等,必须放弃
::marker,改用li::before+position: absolute - 示例:让序号变成蓝色圆点内嵌白字
ol li { position: relative; padding-left: 2.5em; }<br>ol li::before { content: counter(item); position: absolute; left: 0; top: 0.2em; width: 1.6em; height: 1.6em; background: #2563eb; color: white; border-radius: 50%; text-align: center; font-size: 0.8em; line-height: 1.6em; } - 这种写法完全可控,也兼容所有浏览器,只是需手动处理缩进和对齐


















