Is it possible to fix the head for a long html huxtable?

85 Views Asked by At

This works for tables produced with kableExtra which is useful when inspecting long tables. I was wondering if anyone has an idea how this may be doable with huxtable.

Here's an example Rmd to get an idea of what I mean. I'd like the huxtable header to be fixed at the top of the page when scrolling down just like in the kable.

---
output: bookdown::html_document2
---

```{r lib}
library(magrittr)
```

```{r kable}
iris %>%
  head(20) %>%
  kableExtra::kbl(caption = "a caption") %>%
  kableExtra::kable_styling(fixed_thead = TRUE)
```

```{r huxtable}
iris %>%
  head(33) %>%
  huxtable::hux() %>%
  huxtable::set_caption("a caption")
```

Related to: Is it possible to make a huxtable output hoverable?

2

There are 2 best solutions below

0
shafee On BEST ANSWER

Simply set position: sticky for each th element of huxtable tables.

---
output: bookdown::html_document2
---

```{r lib}
library(magrittr)
```

```{r huxtable}
iris %>%
  head(33) %>%
  huxtable::hux() %>%
  huxtable::set_caption("a caption")
```


```{=html}
<style>

table.huxtable th {
  position: sticky;
  top: 0;
  background: white;
}

</style>

```
0
Patrick On

Assuming there are two lines in the huxtable header the accepted answer needs to be adapted as so:

---
output: bookdown::html_document2
---

```{r lib}
library(magrittr)
```

```{r data-prep}
df <- data.frame(COL1_HEAD1 = letters, COL2_HEAD1 = LETTERS)
df <- rbind(df, df)
df[1, ] <- c("HEAD2", "HEAD2")
```

Works for two lined headers:
```{r huxtable-double-line-header}
df %>%
  head(33) %>%
  huxtable::hux() %>%
  huxtable::set_caption("a caption") %>%
  huxtable::set_header_rows(row = c(1, 2), value = TRUE)
```

Works for single lined headers:
```{r huxtable-single-line-header}
df %>%
  head(33) %>%
  huxtable::hux() %>%
  huxtable::set_caption("a caption")
```

```{=html}
<style>

table.huxtable th {
  position: sticky;
  background: white; /* background color prevents content below from showing through */
}

table.huxtable tr:first-child th {
    top: 0;
}

table.huxtable tr:nth-child(2) th {
    top: 30px; /* may need manual adjustment depending on actual height of first row */
}

</style>
```