Search code examples
cssrkableextra

How to center text from cell_spec() in kableExtra using CSS?


I was kindly provided a workaround using the extra_css = argument in cell_spec() from the kableExtra package that enables me to fill the entire cell of the table rather than just the text. However, despite setting align = c("l", "c") in the kbl() call, the output results in the text in the val column not centering.

I'm really hoping to get the text centre aligned for an R Markdown report, so if anyone can suggest a workaround for this, perhaps using CSS, that will be great! Thanks.

library(kableExtra)

set.seed(123)

name <- paste("Name", LETTERS)
val <- rnorm(26, 100, 50)
d <- data.frame(name, val)

d$val <- cell_spec(d$val,
                   background = dplyr::case_when(
                     d$val > mean(d$val) + sd(d$val) ~ "#DBEBF6",
                     d$val < mean(d$val) - sd(d$val) ~ "#FEE7DA",
                     .default = "transparent"
                   ),
                   extra_css = "margin: -8px; padding: 8px; display: flex;",
                   background_as_tile = FALSE
)

kbl(d, escape = FALSE, align = c("l", "c")) %>%
  kable_styling()

enter image description here


Solution

  • library(kableExtra)
    
    set.seed(123)
    
    name <- paste("Name", LETTERS)
    val <- rnorm(26, 100, 50)
    d <- data.frame(name, val)
    
    d$val <- cell_spec(d$val,
                       background = dplyr::case_when(
                         d$val > mean(d$val) + sd(d$val) ~ "#DBEBF6",
                         d$val < mean(d$val) - sd(d$val) ~ "#FEE7DA",
                         .default = "white"
                       ),
                       extra_css = "margin: -8px; padding: 8px; display: flex;",
                       background_as_tile = FALSE
    )
    
    kbl(d, escape = FALSE, align = c("l", "c")) %>%
      kable_styling(full_width = F)
    

    For HTML output you can achieve this by turning off full_width within kable_styling().

    Helpful stuff on that here: https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html