Search code examples
cssrshinydtbslib

Customising DT::datatable using css in a shiny app that uses bslib


I'm trying to apply custom css styling to a DT::datatable in a shiny app. When a user selects a row in the table, I want the selected row to be yellow with black text, instead of the default blue with white text. I'm having trouble doing this successfully when also using the bslib package.

(A similar question was asked here, but I couldn't make the answer work, as I will describe below).

Without bslib, I can successfully apply the css as follows:

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style(
      HTML("table.dataTable tbody tr.selected td {
             color: black !important;
             box-shadow: inset 0 0 0 9999px yellow !important;}"
      )
    )
  ),
  DT::dataTableOutput("test_table")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
    DT::datatable(iris, selection = 'single')
  })
}

shinyApp(ui, server = server)

successful css

However, I'm finding that with bslib themes, I can't use the same method to apply the css.

I've seen these two resources that point to using the bslib::bs_add_rules function to solve this:

Based on those, I've tried variants of the following, but can't seem to make it work:

library(shiny)

ui <- bslib::page_fluid(
  theme = bslib::bs_add_rules(
      bslib::bs_theme(),
      sass::as_sass("table.dataTable tbody tr.selected td {
             color: black !important;
             box-shadow: inset 0 0 0 9999px yellow !important;}"
      )),
  DT::dataTableOutput("test_table")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
      DT::datatable(iris, selection = 'single')
  })
}

shinyApp(ui, server = server)

unsuccessful css


Solution

  • The issue is on the object tag. If you inspect the HTML code you will notice that it should be .table.dataTable tbody tr.active td when you use sass::as_sass, not table.dataTable tbody tr.selected td

    library(shiny)
    
    ui <- bslib::page_fluid(
      theme = bslib::bs_add_rules(
        bslib::bs_theme(),
        sass::as_sass("table.dataTable tbody tr.active td {
                 color: black !important;
                 box-shadow: inset 0 0 0 9999px yellow !important;}"
        )),
      DT::dataTableOutput("test_table")
    )
    
    server <- function(input, output, session) {
      
      output$test_table <- DT::renderDataTable({
        DT::datatable(iris, selection = 'single')
      })
    }
    
    shinyApp(ui, server = server)