如何用自定义CSS让R Markdown生成的Reveal.js无嵌套有序列表显示编号
解决Reveal.js中嵌套描述列表对齐与无嵌套有序列表编号显示问题
问题背景
在R Markdown生成的Reveal.js演示文稿中,为了让有序列表的项目编号和嵌套其中的描述列表(dt)元素对齐,之前采用的方案会隐藏所有有序列表的默认编号,导致没有嵌套描述列表的普通有序列表也丢失了编号。需要调整CSS,同时满足两种场景的显示需求:
- 嵌套描述列表的有序列表保持对齐布局
- 无嵌套的普通有序列表正常显示编号
解决方案
通过CSS的:has()伪类精准控制样式作用范围,只对包含描述列表的有序列表项隐藏默认编号,普通有序列表保留原生编号。
修改后的关键CSS代码
替换原CSS中关于列表样式的部分,修改后的代码如下:
/* 仅隐藏包含描述列表的列表项的默认编号 */ .reveal li:has(dl) { list-style-type: none; } /* 仅在包含嵌套描述列表的有序列表中重置计数器 */ .reveal ol:has(li dl) { counter-reset: css-counter 0; } /* 对嵌套在列表项中的描述列表标题递增计数器 */ .reveal li dl dt { counter-increment: css-counter 1; } .reveal li dl dt:before { content: counter(css-counter) ". "; width: 1rem; display: inline-block; /* 固定编号宽度,保证对齐整齐 */ } .reveal li dl dd { margin-left: 2em; }
代码说明
:has(dl)伪类:精准定位包含描述列表的列表项,只对这类项隐藏默认编号,普通列表项不受影响- 缩小计数器的作用范围:仅在包含嵌套描述列表的有序列表中重置和递增计数器,避免干扰普通有序列表的原生编号逻辑
display: inline-block:确保编号的宽度固定,让嵌套的描述列表标题和有序列表编号对齐更稳定
完整可运行的R Markdown代码
--- author: CLRR date: | | Last Update: `r format(Sys.time(), '%Y/%m/%d')` output: revealjs::revealjs_presentation: self_contained: false reveal_plugins: ["notes", "search"] transition: slide pandoc_args: - --wrap=preserve --- # 嵌套描述列表的有序列表 1. Item A ~ This is A! ~ It's good! 1. Item B ~ This is B! ~ It's new! # 无嵌套的普通有序列表(编号正常显示) 1. Item Alpha 1. Item Bravo 1. Item Charlie ```{css, echo=FALSE} .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 { font-family: 'Roboto', 'Noto Sans JP', sans-serif; } .reveal h1, .reveal h2 { font-family: 'Roboto', 'Noto Sans JP', sans-serif; font-weight: bold; } .reveal code{ font-family: 'Roboto Mono', monospace; } .reveal pre { font-family: 'Roboto Mono', monospace; } .reveal pre code { font-family: 'Roboto Mono', monospace; } .reveal .slide { font-family: 'Roboto', 'Noto Sans JP', sans-serif; } .reveal .footer { font-size: 83%; } .columns { display: flex !important; justify-content: center; align-items: center; } .column { display: inline-block; } .uri { word-break: break-all; } .reveal .speaker-controls { font-family: 'Roboto', 'Noto Sans JP', sans-serif; } /* 仅隐藏包含描述列表的列表项的默认编号 */ .reveal li:has(dl) { list-style-type: none; } /* 仅在包含嵌套描述列表的有序列表中重置计数器 */ .reveal ol:has(li dl) { counter-reset: css-counter 0; } /* 对嵌套在列表项中的描述列表标题递增计数器 */ .reveal li dl dt { counter-increment: css-counter 1; } .reveal li dl dt:before { content: counter(css-counter) ". "; width: 1rem; display: inline-block; /* 固定编号宽度,保证对齐整齐 */ } .reveal li dl dd { margin-left: 2em; }
内容的提问来源于stack exchange,提问作者Carlos Luis Rivera
相关产品推荐
相关产品推荐

