Changing chunk background color in RMarkdown

We can use the class.source option in the code chunk header to provide custom CSS to R Markdown. This is explained in the following post:

Add a CSS class to single code chunks in RMarkdown

Putting together an example, I might set a class called “badCode” then have a bit of CSS to change the background as you might like. Here’s my .Rmd:

---
output: html_document
---

```{css}
.badCode {
background-color: red;
}
```

```{r mtcars}
summary(mtcars)
```

```{r cars, class.source="badCode"}
summary(cars)
```

Leave a Comment