Create a function in Quarto similar to fixed table header in RMarkdown
P粉366946380
2023-08-29 17:12:38
<p>I have been trying to render a sticky table header from the <code>table1</code> R package in Quarto, as I successfully do in RMarkdown. However, Quarto doesn't seem to recognize my .css file, or (more likely) I'm missing something. </p>
<p>I included the CSS files with the .rmd and .qmd to be able to reproduce. I've also included inline html code to create a scroll box so that the table header is fixed. </p>
<p>style.css:</p>
<pre class="brush:php;toolbar:false;">.Rtable1 th {
border: 0;
text-align: center;
padding: 0.5ex 1.5ex;
margin: 0;
background-color: #D3D3D3;
color: black;
position: sticky;
top: 0;
border-top: 2pt solid black;
border-bottom: 1pt solid black;
}</pre>
<p>car.rmd:</p>
<pre class="brush:php;toolbar:false;">---
title: "Cars"
output:
html_document:
css: styles.css
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE)
```
```{r}
library(table1)
library(tidyverse)
cars <- mtcars
cars$cars <- rownames(cars)
cars <-
cars |>
mutate(
gear = factor(gear)
)
```
<div style="height:450px; width: 500; overflow:auto; border:1.5px solid gray; padding:1.5%">
```{r}
table1::table1(
~ cars | gear,
data = cars
)
```
</div></pre>
<p>car.qmd:</p>
<pre class="brush:php;toolbar:false;">---
title: Cars
format:
html:
toc: true
css: styles.css
knitr:
opts_chunk:
echo: false
message: false
---
```{r}
library(table1)
library(tidyverse)
cars <- mtcars
cars$cars <- rownames(cars)
cars <-
cars |>
mutate(
gear = factor(gear)
)
```
<div style="height:450px; width: 500; overflow:auto; border:1.5px solid gray; padding:1.5%">
```{r}
table1::table1(
~ cars | gear,
data = cars
)
```
</div></pre>
<p>This is the first question I've posted, so I hope I submitted a good reprex. Thank you for taking the time to read. Hope to get some good advice. wish all the best! </p>
One thing to note is that unlike R-markdown, in the HTML output generated by quarto, whatever is generated from the code block is wrapped with two consecutive divs that have the class name
cell
andcell-output-display
.And the class
cell-output-display
has the CSS attributeoverflow-x
set toauto
, which is theposition of the header: sticky
The main reason why it doesn't work (Click here to see the reason).Therefore, we only need to override this attribute of class
cell-output-display
to solve the problem.cars.qmd
(Note that I used pandoc divs instead of inline html tags to define a class where we will override this property.)
styles.css