使用R+gt()+Quarto生成HTML报告时无法降低表格内边距
如何在不依赖动态div id的情况下消除gt()表格的上下内边距
使用R + gt() + Quarto渲染HTML报告,需要将下图红框中三个表格的上下内边距设为0px。之前通过div id实现了效果,但每次运行Quarto报告时div id都会变化,因此需要不依赖div id的解决方案。

原本以为是CSS问题,但所有CSS方案都没成功,不确定是否需要通过gt()或Quarto本身解决。
开发者工具中的有效修改
在浏览器开发者工具中,将以下代码里的padding-top和padding-bottom从10px改为0px即可达到预期效果:
<div class="cell-output-display"> <div id="rwxpuyzumb" style="padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;"> ... 其他代码 ... </div>
自定义CSS的异常现象
但在自定义styles.css中尝试选择该元素时,出现了奇怪的现象:所有选择器都能选中目标元素,但无法将内边距降至10px以下,不过可以增加内边距。以下是带注释的styles.css代码:
/* CSS */ .gt_table { margin-top: 0px !important; margin-bottom: 0px !important; } /* 内边距大于10px时可增加,但无法减少 */ div.cell-output-display{ padding-top: 0px !important; padding-bottom: 0px !important; border: 2px dotted green; } /* 可成功减少内边距,但每次运行报告div id会变化 */ #rwxpuyzumb{ padding-top: 0px !important; padding-bottom: 0px !important; border: 2px solid red; } /* 可选中目标表格,但仅能增加内边距 */ .cell-output-display:nth-of-type(2){ padding-top: 0px !important; padding-bottom: 50px !important; border: 2px solid yellow; } /* 可选中目标表格,但仅能增加内边距 */ .cell-output-display:nth-of-type(3){ padding-top: 0px !important; padding-bottom: 0px !important; border: 2px solid blue; }
生成表格的R/Quarto代码
以下是生成这三个表格的R/Quarto代码:
--- title: "gt_padding" format: html: css: styles.css editor_options: chunk_output_type: console --- ```{r} #| include: false library(dplyr) library(gt) dat <- mtcars |> as_tibble(rownames = "car") |> head(4) tab1 <- dat |> select(car,2:3) |> gt() tab2 <- dat |> select(car,4:7) |> gt() tab3 <- dat |> select(car,8:11) |> gt()
#| echo: false tab1 tab2 tab3
编辑补充:已将原始HTML和CSS上传至代码仓库。 --- 内容的提问来源于stack exchange,提问作者seansteele
相关产品推荐
相关产品推荐

