Add CSS to modify the look of the app
CSS is an extremely popular markup language that is used to tell the browser how to display elements on a page. You need to use CSS if you want to deviate from the default look-and-feel of Shiny and want to customize the appearance of different items in your app.
Recall that CSS is comprised of a set of rules, where each rule is a property: value
pair associated with an element on the page. It's possible to include CSS in your app by writing it in a separate file and importing it with includeCSS()
, but in this course we will use the simpler approach of placing the CSS code inside tags$style()
in the UI.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
- Write CSS rules to modify the app in the following ways:
- Change the background color of the download button to orange (line 5).
- Change the text size of the download button to 20 pixels (line 8).
- Change the text color of the table to red (line 13).
- Add these CSS rules to the Shiny app (line 20).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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)