Search code examples
javascriptcssrflextable

Changing background color on sticky multi-row flextable header


Hi there – below I have a scrolling flextable with multiple headers. Whenever I scroll, the table body text can be seen behind the table header (i.e., the table header is transparent). I'm looking for a way to set the table header background color to white.

I've tried utilizing the extra_css portion of the set_table_properties function – this worked to make the multiple headers "sticky", however the code for background-color is not generating white as desired. I've also tried adjusting the z-index, which hasn't worked either.

I saw that utilizing Javascript may be one solution, however I've been unsuccessful in applying this for my specific use case. Any suggestions on resolving this issue are greatly appreciated!


title: "Untitled" output: html_document

library(dplyr)
library(flextable)


tbl1 <- flextable(mtcars) %>%
  add_header_row(top = TRUE, values = c("","header 1", "header 2"), colwidths = c(1,5,5)) %>%
  set_table_properties(
    layout = "autofit",
    opts_html = list(
      scroll = list(
        height = "300px",
        freeze_first_column = F
      ),
      extra_css = "
          thead{
          position: sticky;
          top: 0;
          width: 100%;
          background-color: white;
          z-index: 99;
      }
      "
    )
  )


What the table looks like after scrolling


Solution

  • You need to use function bg() for that:

    library(dplyr)
    library(flextable)
    
    
    tbl1 <- flextable(mtcars) %>%
      bg(bg = "white", part = "all") %>% 
      add_header_row(top = TRUE, values = c("","header 1", "header 2"), colwidths = c(1,5,5)) %>%
      set_table_properties(
        layout = "autofit",
        opts_html = list(
          scroll = list(
            height = "300px",
            freeze_first_column = FALSE
          ),
          extra_css = "
              thead{
              position: sticky;
              top: 0;
              width: 100%;
              z-index: 99;
          }
          "
        )
      )