rr-markdownbookdown

Changing code blocks style in bookdown chapters


I am trying to change the style of code blocks in bookdown for the html output. As instructed in the official documentation here I am doing the following:

```{r class.source="bg-danger", class.output="bg-warning"}
mtcars[1:5, "mpg"]
```

This effectively changes the style as expected when applying it to a single RMarkdown document. However, the parameters class.source="bg-danger", class.output="bg-warning" have no effect within a chapter in a bookdown document.

Am I missing somethig?

UPDATE:

I have also tried using a custom style. I included the following in my style.css file.

.python-output {
  background-color: yellow;
}

and then used:

class.source="python-output"

but still, the style was not applied.


Solution

  • The classes described in the R Markdown Cookbook, e.g. applied by using

    ```{r class.source="bg-danger", class.output="bg-warning"}
    mtcars[1:5, "mpg"]
    ```
    

    are Bootstrap helper classes. Using bookdown, e.g. with bookdown::gitbook, does not carry any Bootstrap style sheet and so applying these classes will not have an effect (This is maybe different with other book types like bs4_book). I would also not include a Bootstrap style sheet in a GitBook because this can have several side effects (GitBook has its own styles).

    However, as an alternative one could use custom CSS and your approach to define this for certain classes is already a good start. In order to make it work, it is necessary to define more specific selectors because otherwise your CSS gets overwritten (or you use !important, but this is in general not the best approach). As an example,

    ```{r class.source = "python-output"}
    mtcars[1:5, "mpg"]
    ```
    

    could be supplied with a yellow background color by defining

    .book .book-body .page-wrapper .page-inner section.normal pre.python-output {
      background-color: yellow;
    }
    

    in style.css.

    enter image description here