Michael Toth
Michael Toth

Reputation: 85

Is there a way to use knitr's css class options when using kable tables?

I recently read about knitr's css classes for chunks as discussed in this question and this example.

In general, this seems to work great. The trouble I'm having is that these options no longer seem to work if the output you're using is a kable. The example below illustrates what I'm talking about. In the first two chunks, I'm able to successfully add the css class bg-success to my output, but the third chunk does not apply this.

Inspecting the output html file, I find that the first two chunks are wrapped in <pre class='bg-success'>...</pre> html blocks while the third chunk is wrapped in a <table class=table table-condensed>...</table> html block. The bg-success class isn't picked up anywhere here.

Has anybody gotten knitr's class.output options to work with kable outputs? Is there a clean way to do this? I know that I could wrap the code chunk in divs and apply the class there, but that's messy and I would prefer to do this cleanly if possible.

---
title: "My Test"
output: html_document
---


\```{r setup, include=FALSE}
library(knitr)

knitr::opts_chunk$set(
    message = FALSE,
    warning = FALSE)
\```

Class works when applied to text:

\```{r working, class.output='bg-success'}
paste("Normal", "R chunk", "output!!")
\```

Class works when applied to data frame:

\```{r working_table, class.output='bg-success'}
head(iris)
\```

Class does not work when applied to kable output:

\```{r not_working, class.output='bg-success'}
kable(head(iris))
\```

Upvotes: 0

Views: 1407

Answers (1)

Radovan Miletić
Radovan Miletić

Reputation: 2821

Add the class bg-success to the table thru the table.attr argument:

knitr::kable(head(iris), table.attr = "class=\'bg-success\'") %>% 
  kableExtra::kable_styling()

I realized that you need to modify the style of HTML table, passing class/argument to kable_styling function.
Apparently, there is no need to specify format argument:

knitr::kable(head(iris), table.attr = "class=\'bg-success\'", format = "html") %>% 
  kableExtra::kable_styling()

Also, you need to include library(kableExtra) to {r setup}.

You may find more info about table.attr argument at section 13.1.11 Customize HTML tables

Upvotes: 1

Related Questions