Knitr style table with CSS
If you take your .Rmd file and the modified CSS file below, you can obtain your desired result with:
knitr::knit2html('my-report.RMD', stylesheet = 'flat-table.css')
Here's the result:
Here is an updated flat-table.css:
.flat-table {
display: block;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 115%;
overflow: auto;
width: auto;
}
th {
background-color: rgb(112, 196, 105);
color: white;
font-weight: normal;
padding: 20px 30px;
text-align: center;
}
td {
background-color: rgb(238, 238, 238);
color: rgb(111, 111, 111);
padding: 20px 30px;
}
If you only have a small amount of customisation that you want to do, you can consider including the CSS directly within the RMarkdown file. Markdown will pass the CSS directly through provided it is enclosed <style> </style>
. Here is a full example:
---
output: html_document
---
# Test Project
<style>
.flat-table {
display: block;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 115%;
overflow: auto;
width: auto;
}
thead {
background-color: rgb(112, 196, 105);
color: white;
font-weight: normal;
padding: 20px 30px;
text-align: center;
}
tbody {
background-color: rgb(238, 238, 238);
color: rgb(111, 111, 111);
padding: 20px 30px;
}
</style>
```{r}
knitr::kable(mtcars[1:5, 1:5])
```
Advanced Formatting
This guide provides lots of useful information on CSS styles for tables. You can achieve some cool things with a few lines of CSS. For example, you can make the row of the table highlight on Hover:
tbody tr:hover {
background: yellow;
}
Note that a lot of table styles use some form of JavaScript to get the formatting working, and also may make changes which affect the rest of the document. You are best sticking to the thead
and tbody
tags.