R tableHTML add_css text-align centre not working in Shiny

970 Views Asked by At

I'm trying to style a table in a Shiny app using the tableHTML package in R.

When I use the tableHTML() function in R it produces exactly what I want. I use the add_css_column to align the text in the column to the centre. However when I use it in a Shiny app the headers end up left aligned and the rows centre aligned. Any ideas how I can fix this?

output$viewers_website_top <- renderUI({ 
  tableHTML(website_index, rownames = FALSE, widths=c(200,200)) %>%
    add_css_column(css = list("text-align", "center"), 
                   column_names = names(website_index)) 
})
1

There are 1 best solutions below

0
On BEST ANSWER

This is a common issue with bootstrap 3 unfortunately. Whenever you use shiny it loads up a bootstrap 3 css (immediately) which makes it difficult to overwrite.

As for the solution to this using add_css_header would probably solve this one. add_css_header would change the th tag of the HTML table to the one you like (whereas add_css_header would change the td tags below the headers):

output$viewers_website_top <- renderUI({ 
  tableHTML(website_index, rownames = FALSE, widths=c(200,200)) %>%
    add_css_header(css = list("text-align", "center"), 
                   headers = 1:ncol(website_index)) 
})

Another thing you can do is to add a separate css file with shiny::includeCSS. There is more info here and here on how to use includeCSS.

In the css file you need to write:

.table_website_index th {
  text-align: center;
}

And that should do it!

P.S. table_website_index is the class the package assigns to the table which you can also change with the class argument.

P.S.2 I am the developer - thanks for using the package :)