Style knitr Code Output Appearance in HTML with Custom CSS Classes

Apply custom CSS classes to code chunk outputs to differentiate between regular outputs and messages, warnings, and errors.

R
knitr
R Markdown
Tips
Author

Garrick Aden-Buie

Published

March 5, 2019

Create awesome-looking, content-dependent output styles in HTML with knitr’s new class.* chunk options.

Create awesome-looking, content-dependent output styles in HTML with knitr’s new class.* chunk options.

Last week, I learned that you can apply a custom CSS class to code chunk outputs using knitr’s class.output, thanks to a two-year-old pull request from Ian Lyttle.

At the time, I was working on customizing CSS classes of the code chunks in my blog after being inspired by the impeccable styling of Brodie Gaslam’s blog. What I like most are the subtle visual clues that link code inputs and outputs by keeping both source and output inside the same box. I have a plan to do something similar on this blog using custom source and output classes via the class.output and class.source chunk options.

But I quickly discovered that the class.output class is only applied to standard code output, and not the “side effect” chunk outputs, such as messages, warnings and errors.

I opened an issue in knitr and, amazingly, three days later my wishes were granted: You can now use the chunk options class.message, class.warning, and class.error to customize the CSS class of outputs of each type.

The new feature will be available in version 1.22 when it makes it to CRAN, or now from GitHub.

Using this feature, you can get nicely formatted chunk outputs. Here’s a minimal example generated from this rmarkdown source.