7.4 Scrollable code blocks (*)

When you have large amounts of code and/or verbatim text output to display on an HTML page, it may be desirable to limit their heights. Otherwise the page may look overwhelmingly lengthy, and it will be difficult for those who do not want to read the details in the code or its text output to skip these parts. There are multiple ways to solve this problem. One solution is to use the code_folding option in the html_document format. This option will fold code blocks in the output and readers can unfold them by clicking a button (see Section 7.5 for more details).

The other possible solution is to make the code blocks scrollable within a fixed height when they are too long. This can be achieved by the CSS properties max-height and overflow-y. Below is a full example with the output in Figure 7.3:

  1. ---
  2. title: Scrollable code blocks
  3. output: html_document
  4. ---
  5. ```{css, echo=FALSE}
  6. pre {
  7. max-height: 300px;
  8. overflow-y: auto;
  9. }
  10. pre[class] {
  11. max-height: 100px;
  12. }
  13. ```
  14. We have defined some CSS rules to limit the height of
  15. code blocks. Now we can test if these rules work on code
  16. blocks and text output:
  17. ```{r}
  18. # pretend that we have a lot of code in this chunk
  19. if (1 + 1 == 2) {
  20. # of course that is true
  21. print(mtcars)
  22. # we just printed a lengthy data set
  23. }
  24. ```
  25. Next we add rules for a new class `scroll-100` to limit
  26. the height to 100px, and add the class to the output of
  27. a code chunk via the chunk option `class.output`:
  28. ```{css, echo=FALSE}
  29. .scroll-100 {
  30. max-height: 100px;
  31. overflow-y: auto;
  32. background-color: inherit;
  33. }
  34. ```
  35. ```{r, class.output="scroll-100"}
  36. print(mtcars)
  37. ```

Scrollable code blocks using custom CSS.

FIGURE 7.3: Scrollable code blocks using custom CSS.

In the above example, we defined a global maximum height of 300px for all code blocks. Remember that code blocks are placed in <pre> tags in the HTML output. Then we limited the height of <pre> blocks to 100px with class attributes. That is what the CSS selector pre[class] means. By default, text output will be contained in <pre> </pre>, and R code blocks are contained in <pre class="r"> </pre> (note that the <pre> tag has a class attribute here).

The height of the text output from the second R code chunk is also 100px. That is because we assigned a custom class name scroll-100 to the output, and defined the maximum height to be 100px.

If you want to specify different maximum heights for individual code blocks, you may see the example in Section 12.3.