開始使用免費開始

加入 CSS 來調整應用程式外觀

CSS 是一種非常普及的標記語言,用來告訴瀏覽器應該如何在頁面上呈現各個元素。當你想要跳脫 Shiny 的預設外觀並自訂應用程式中不同項目的樣式時,就需要使用 CSS。

回想一下,CSS 是由一組規則組成,每個規則都是和頁面元素相關的 property: value 配對。你可以把 CSS 寫在獨立檔案中,並透過 includeCSS() 匯入到你的應用程式。不過在本課程中,我們會採用更簡單的方式:把 CSS 程式碼放在 UI 裡的 tags$style()

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

  • 撰寫 CSS 規則,將應用程式做以下修改:
    • 將下載按鈕的背景顏色改為橘色(第 5 行)。
    • 將下載按鈕的文字大小改為 20 像素(第 8 行)。
    • 將表格的文字顏色改為紅色(第 13 行)。
  • 把這些 CSS 規則加入 Shiny 應用程式(第 20 行)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

my_css <- "
#download_data {
  /* Change the background color of the download button
     to orange. */
  background: ___;

  /* Change the text size to 20 pixels. */
  font-size: ___px;
}

#table {
  /* Change the text color of the table to red. */
  color: ___;
}
"

ui <- fluidPage(
  h1("Gapminder"),
  # Add the CSS that we wrote to the Shiny app
  tags$style(___),
  tabsetPanel(
    tabPanel(
      title = "Inputs",
      sliderInput(inputId = "life", label = "Life expectancy",
                  min = 0, max = 120,
                  value = c(30, 50)),
      selectInput("continent", "Continent",
                  choices = c("All", levels(gapminder$continent))),
      downloadButton("download_data")
    ),
    tabPanel(
      title = "Plot",
      plotOutput("plot")
    ),
    tabPanel(
      title = "Table",
      DT::dataTableOutput("table")
    )
  )
)

server <- function(input, output) {
  filtered_data <- reactive({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
  
  output$table <- DT::renderDataTable({
    data <- filtered_data()
    data
  })

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      data <- filtered_data()
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    data <- filtered_data()
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
編輯並執行程式碼