For single Rmarkdown documents or Shiny apps, styling with CSS or using custom themes such as shinythemes works well.

As an R developer, designing a default style sheet is difficult. The developer wants to provide a theme that works and looks good, while providing customization options for users.

This article will briefly show how to use the sass R package to generate style sheets based on user input.

Variables

Sass variables are key to generating dynamic CSS. You can define components of your styling at runtime based on user input.

It is best practice to define your variables separately, and then import them into the main Sass file. For example, we’ll define a color variable and use it to set the body’s background color.

The following shiny app will demonstrate this example. We’ll use Dean Attali’s colourpicker to choose a color and write it to _variables.scss.

Then the app compiles new-style.scss and renders the new style.

Functions

If we choose a background color that is too dark, we won’t be able to read the title Sass Example. Therefore, we need to make the font color depend on the background color.

Sass offers many built-in functions that help with dynamic styling, and you can always write your own.

In this shiny example app, the font color now depends on the background color, switching between black and white as necessary.

CSS Formatting

Sass can also produce human readable or production ready CSS, depending on the need.

Here we’ll convert the human readable Sass to minified CSS.

library(sass)
sass(new_style, options = sass_options(output_style = "compressed"))
body{background-color:#fff}h1{color:#000}.shiny-plot-output{max-width:100%}