Zeus
Zeus

Reputation: 1590

Datatable column auto resizing

I have a shiny app with two datatables side by side. Are there any options to automatically resize the table or column when the width of the window is changed?

Ideally I'd like to see all columns (maybe reduced font size) with no X scroll bar in both tables, and the tables side by side. The code below makes the tables overlap as the window size reduces.

library(shiny)
library(DT)

shinyApp(
    ui = fluidPage(
      fluidRow(
        column(5,
               dataTableOutput('table.1')
        ),
        column(2
        ),
        column(5,
               dataTableOutput('table.2')
        )
      )
    ),
    server = function(input, output) {
      output$table.1 <- renderDataTable(iris,options = list(autoWidth = TRUE))

      output$table.2 <-  renderDataTable(iris,options = list(autoWidth = TRUE))
    }
  )

Upvotes: 0

Views: 2303

Answers (1)

mlegge
mlegge

Reputation: 6913

As mentioned in the comments CSS can handle this for you using viewport based text sizes. I took the liberty of also including the syntax for specifying a maximum text size in case users have exceptionally wide screens:

library("shiny")
library("DT")

shinyApp(
  fluidPage(
    tags$head(
      tags$style(
        HTML("
          .datatables {
              font-size: 1.5vw;
          }

          @media screen and (min-width: 1024px) {
              .datatables {
                  font-size: 12px;
              }
          }
        ")
      )
    ),
    dataTableOutput("iris")),
  function(input, output) {
    output$iris = renderDataTable({
      datatable(iris)
    })
  }
)

This answer has more on viewport percentage lengths and this answer provides the example for the max size.

Upvotes: 2

Related Questions