18.3 Integrate CSS files in your {shiny} app

CSS can be included in shiny apps in a few ways:

  • inline
  • in your ui definition
  • in an imported file

18.3.1 Inline

ui3 <- function(){
  tagList(
    h2(style = "color:red;", "This is red")
  )
}
shinyApp(ui3, empty_server)
print(ui3())
## <h2 style="color:red;">This is red</h2>

18.3.2 Using tags$style()

ui4 <- function(){
  tagList(
    tags$style(
      "h2{
        color:red;
      }"
    ), 
    h2("This is red")
  )
}
print(ui4())
## <style>h2{
##         color:red;
##       }</style>
## <h2>This is red</h2>

18.3.3 Using external files

Provided you have this in the path ./www/style.css

h2 {
    color: red;
}

Then the following will incorporate that css into your vanilla shiny app.

ui5 <- function() {
  tagList(
    tags$link(
      rel = "stylesheet",
      type = "text/css",
      href = "www/style.css"
    ), 
    h2("This is red")
  )
}

A golem-based shiny app has the command golem_add_external_resources() in the UI definition. This function pulls in any CSS or JS files. But, to add those CSS / JS files you have to use the correct golem workflow:

# For CSS
golem::add_css_file("style")

This adds the file inst/app/www/style.css to your package.

There are alternative ways to include CSS. In “Outstanding User Interfaces with Shiny”, the author recommends creating a dependency, and then including it as a tag in your UI:

# R/style.R
css_dep <- function() {
  htmlDependency(
    name = "css dep", version = "1.0", src = path_to_css, stylesheet = filename
  )
}

# In ui.R
... tagList(tag, css_dep)