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:
---
title: Scrollable code blocks
output: html_document
---
```{css, echo=FALSE}
pre {
max-height: 300px;
overflow-y: auto;
}
pre[class] {
max-height: 100px;
}
```
We have defined some CSS rules to limit the height of
code blocks. Now we can test if these rules work on code
blocks and text output:
```{r}
# pretend that we have a lot of code in this chunk
if (1 + 1 == 2) {
# of course that is true
print(mtcars)
# we just printed a lengthy data set
}
```
Next we add rules for a new class `scroll-100` to limit
the height to 100px, and add the class to the output of
a code chunk via the chunk option `class.output`:
```{css, echo=FALSE}
.scroll-100 {
max-height: 100px;
overflow-y: auto;
background-color: inherit;
}
```
```{r, class.output="scroll-100"}
print(mtcars)
```
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.