Search code examples
jqueryrshinydt

How to right align columns of DataTable in R Shiny?


From this post I gather we should define an alignRight CSS class with the desired alignment:

# ui.R
sidebarLayout(...,
    mainPanel(
        tags$head(
            tags$style(".alignRight { align: right; }", media = "all", type = "text/css")
        ),
        ...     # content with call to dataTableOutput("myTable")
    )
)

and then when creating the DataTable, use the aoColumnDefs option to set class of the desired columns to alignRight:

# server.R
shinyServer(
    function(input, output) {...
        output$myTable <- renderDataTable(...,
            options = list(
                aoColumnDefs = '[{"aTargets": [7, 9, 10], "sClass": "alignRight"}]'
            )
        )
    }
)

However, this has had no effect on my DataTable, when remains left aligned for all columns. I thought a simple alignment issue would be easy to sort out, but after many hours, apparently not so. Any ideas would be much appreciated.


Solution

  • This:

    library(shiny)
    
    runApp(list(
      ui = basicPage(
        tags$head(tags$style(".table .alignRight {color: blue; text-align:right;}")),
        h2('The mtcars data'),
        dataTableOutput('mytable')
      ),
      server = function(input, output) {
        output$mytable = renderDataTable({
          mtcars
        }, options =list(aoColumnDefs = list(list(sClass="alignRight",aTargets=c(list(3),list(4),list(5))))  ))
      }
    ))
    

    worked for me and might help you model the CSS right for your situation. I only used blue since it helps show if other parts of the td formatting are working even if one might not be.