6.5 Bootstrap & Themes

Shiny uses the bootstrap toolkit for styling.

Here’s the strapline for bootstrap:

Quickly design and customize responsive mobile-first sites with Bootstrap,
the world’s most popular front-end open source toolkit, featuring Sass
variables and mixins, responsive grid system, extensive prebuilt components,
and powerful JavaScript plugins.

What does that mean?

  • Responsive
    • The page alters layout / appearance for different screen widths
  • Sass variables and mixins
    • These are tools that reduce the amount of repetition when writing CSS
  • Prebuilt components
    • You don’t have to write your own button, navbar, etc … classes from scratch
  • Javascript plugins
    • eg, for using dropdowns

So bootstrap solves lots of challenges for us

Use package {bslib} to work with bootstrap in R

To modify themes:

bslib::bs_theme(
  # colours in RGB
  bg = "#202123", # background
  fg = "#B8BCC2", # foreground
  primary = NULL,
  secondary = NULL,
  success = NULL,
  info = NULL,
  warning = NULL,
  danger = NULL,
  # fonts
  base_font = list(bslib::font_google("Pacifico", local = TRUE), "sans-serif"),
  code_font = NULL,
  heading_font = NULL
  # further options ...
)

Or use bootswatch to pick a prebuilt theme:

bslib::bs_theme(bootswatch = "sandstone")

Then use a theme in your UI definition:

theme_dark <- bslib::bs_theme(
  bootswatch = "darkly",
  base_font = list(bslib::font_google("Pacifico", local = TRUE), "sans-serif")
)

ui_with_bs <- fluidPage(
  theme = theme_dark
)

cat(
  shiny:::renderPage(ui_with_bs)
)
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="application/shiny-singletons"></script>
  <script type="application/html-dependencies">jquery[3.6.0];shiny-css[1.9.1];shiny-busy-indicators[1.9.1];shiny-javascript[1.9.1];bootstrap[5.3.1];Pacifico[0.4.9];bs3compat[0.8.0]</script>
<script src="jquery-3.6.0/jquery.min.js"></script>
<link href="shiny-css-1.9.1/shiny.min.css" rel="stylesheet" />
<link href="shiny-busy-indicators-1.9.1/busy-indicators.css" rel="stylesheet" />
<script src="shiny-javascript-1.9.1/shiny.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<link href="bootstrap-5.3.1/bootstrap.min.css" rel="stylesheet" />
<script src="bootstrap-5.3.1/bootstrap.bundle.min.js"></script>
<link href="Pacifico-0.4.9/font.css" rel="stylesheet" />
<script src="bs3compat-0.8.0/transition.js"></script>
<script src="bs3compat-0.8.0/tabs.js"></script>
<script src="bs3compat-0.8.0/bs3compat.js"></script>
</head>
<body>
  <div class="container-fluid"></div>
</body>
</html>