如何在Quarto HTML文档中设置嵌套式图与列表标题编号?
解决Quarto HTML文档图/列表嵌套编号问题
方法一:Quarto原生交叉引用配置(推荐)
Quarto内置的交叉引用系统支持自定义编号格式,直接通过YAML配置即可实现需求,无需额外代码。
在文档开头的YAML元数据(或项目根目录的_quarto.yml)中添加以下配置:
--- title: "你的文档标题" number-sections: true # 开启章节自动编号 crossref: fig: prefix: "图" # 图标题前缀 numbering: "chapter.section.subsection.serial" # 编号格式:章.节.子节.小节内顺序号 tbl: prefix: "表" # 表标题前缀 numbering: "chapter.section.subsection.serial" lst: prefix: "列表" # 代码块/列表标题前缀 numbering: "chapter.section.subsection.serial" ---
配置说明:
number-sections: true:启用章、节、子节的自动编号numbering: "chapter.section.subsection.serial":指定编号规则,其中:chapter:章编号section:节编号subsection:子节编号(若当前层级无子节,会自动省略该部分)serial:当前小节内的图/表/列表顺序号(每个小节内从1重新计数)
配置后编号会自动匹配层级:
- 1.1节的第一张图:
图1.1.1 - 2.2.1子节的前两张图:
图2.2.1.1、图2.2.1.2
方法二:CSS备选方案
如果原生配置无法满足特殊需求,可以通过CSS自定义计数器实现嵌套编号:
将以下CSS代码添加到文档的YAML(或单独的CSS文件)中:
/* 初始化全局计数器 */ body { counter-reset: chapter section subsection fig tbl lst; } /* 章级计数器:进入新章时重置节、子节和图的计数器 */ h1[data-number] { counter-reset: section fig tbl lst; counter-increment: chapter; } /* 节级计数器:进入新节时重置子节和图的计数器 */ h2[data-number] { counter-reset: subsection fig tbl lst; counter-increment: section; } /* 子节级计数器:进入新子节时重置图的计数器 */ h3[data-number] { counter-reset: fig tbl lst; counter-increment: subsection; } /* 自定义图编号 */ .quarto-figure .caption-number:before { content: "图" counter(chapter) "." counter(section) "." counter(subsection) "." counter(fig); counter-increment: fig; } /* 处理无小节的场景:隐藏多余的分隔点 */ h2[data-number]:not(:has(+ h3[data-number])) ~ .quarto-figure .caption-number:before { content: "图" counter(chapter) "." counter(section) "." counter(fig); } h1[data-number]:not(:has(+ h2[data-number])) ~ .quarto-figure .caption-number:before { content: "图" counter(chapter) "." counter(fig); } /* 同理扩展表的编号 */ .quarto-table .caption-number:before { content: "表" counter(chapter) "." counter(section) "." counter(subsection) "." counter(tbl); counter-increment: tbl; } h2[data-number]:not(:has(+ h3[data-number])) ~ .quarto-table .caption-number:before { content: "表" counter(chapter) "." counter(section) "." counter(tbl); } h1[data-number]:not(:has(+ h2[data-number])) ~ .quarto-table .caption-number:before { content: "表" counter(chapter) "." counter(tbl); }
CSS思路:
- 利用CSS计数器跟踪章、节、子节的层级编号
- 每个层级标题出现时,重置下一级和图/表的计数器
- 通过
:before伪元素生成自定义编号,并自动处理无层级的场景
内容的提问来源于stack exchange,提问作者StatsStudent
相关产品推荐
相关产品推荐

