开始使用免费开始使用

添加 CSS 来修改应用外观

CSS 是一种非常常用的标记语言,用来告诉浏览器如何在页面上呈现各类元素。若您希望不采用 Shiny 的默认外观,并自定义应用中不同组件的样式,就需要使用 CSS。

回顾一下,CSS 由一组规则组成,每条规则是与页面元素关联的 property: value 键值对。您可以将 CSS 写在单独的文件中,并通过 includeCSS() 导入到应用中;不过在本课程中,我们将采用更简单的方法:把 CSS 代码放在 UI 里的 tags$style() 中。

本练习是课程的一部分

案例研究:使用 R 的 Shiny 构建 Web 应用

查看课程

练习说明

  • 编写 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)
编辑并运行代码