Search code examples
cssrr-markdownxaringan

Customize css for input/output chunks in xaringan


I use xaringan to make presentations and would like to customize the CSS for the input and output R chunks.

Initially, I thought I could use the class.source and class.output arguments from knitr to set the CSS classes.

knitr::opts_chunk$set(class.source = "foobar", 
                      class.output = "bg-warning")

However, those global actions don't seem to play nicely with xaringen. The following minimal example

---
title: Change the chunk style
output:
  xaringan::moon_reader
---


```{r}
knitr::opts_chunk$set(class.source = "foobar", 
                      class.output = "bg-warning")
```

```{r}
mtcars[1:5, "mpg"]
```

produces the following rendering

enter image description here

If the output is set to htlm_document then everything play nicely, but that doesn't fix it for the xaringan presentation.


Solution

  • These chunk options won't work for xaringan because xaringan doesn't use Pandoc's Markdown syntax but remark.js's. That is, they generate ```{.r .class}, which only works for Pandoc's Markdown. I don't have time to support them in xaringan, but if you want to contribute a pull request on Github, here is the place to start: https://github.com/yihui/xaringan/blob/2ad2a6d/R/render.R#L195-L204 Basiscally, you wrap the source/output character strings inside .class[], which is remark.js's syntax for adding classes to elements.

    Without a patch, you can only apply a class name to the whole output, and style the code blocks inside the class, e.g.,

    ---
    title: Change the chunk style
    output:
      xaringan::moon_reader
    ---
    
    ```{css, echo=FALSE}
    /* R code */
    .foobar code.r {
      font-weight: bold;
    }
    /* code without language names */
    .foobar code[class="remark-code"] {
      display: block;
      border: 1px solid red;
    }
    ```
    
    .foobar[
    ```{r}
    mtcars[1:5, "mpg"]
    ```
    ]