htmlcssrknitrr-markdown

Adding a table of contents on the left side with HTML document in Rmarkdown


Im trying to add a table of contents in a HTML document produced by Rmarkdown. First of all, I found this answer, which seems a easy way to do, adding a CSS file whit this code in the HTML file:

#TOC {
  position: fixed;
  left: 0;
  top: 0;
  width: 200px;
  height: 100%;
  overflow:auto;
}
body {
  max-width: 800px;
  margin: auto;
  margin-left:210px;
  line-height: 20px;
}

But I would like to modify the CSS from the Rmarkdown. To solve the problem I found this other post, how to add custom CSS tags. But is not exactly what Im looking for, and dont know how to mix this to answers in a properly way.

My code look like this:

---
title: "R"
output: html_document
toc: yes
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r results="asis"}
cat("TOC {
  position: fixed;
  left: 0;
  top: 0;
  width: 200px;
  height: 100%;
  overflow:auto;
}
body {
  max-width: 800px;
  margin: auto;
  margin-left:210px;
  line-height: 20px;
}")
```

I think Im missing something important. Thanks in advance!


Solution

  • As shown in the code of your first answer, you need to add these in your YAML header, but you need to be careful with the spaces:

    title: "cssTest"
        output:
        html_document:
          css: custom.css
          toc: yes
    

    Then, the css file should be an external css file. Out of your Rmd code. Here, it is a file in the same directory than your Rmd file, which is called custom.css.