使用 CSS 自定义代码块
您可以使用 fenced_code_attributes 将 CSS 类(或几个不同的类)添加到某些代码块。为此,请将此选项添加到 YAML 标头并使用 knit_hoooks$set() 定义一个新钩子(有关详细信息,请参阅 Hooks)。之后,我们可以使用块选项class = 'myCssClass'。
在下面的示例中,我们定义了一个类.smallCode,它为块设置了一定的宽度和较小的字体大小。在最终文档中,结果如下所示:
<pre class="sourceCode r smallCode">
<code class="sourceCode r">
THE CODE WE PRODUCED
</code>
</pre>
如您所见,我们刚刚将smallCode 类添加到<pre> 元素!耶!
您可以修改任何内容,包括字体样式、背景等等。有关可能性的概述,请查看此CSS Tutorial
包装源代码
如果您想包装源代码,可以使用块选项tidy=T 及其选项width.cutoff(也在下面的示例中实现)。
可重现的例子:
---
title: "Customized Code Chunks"
author: Martin Schmelzer
date: March 22, 2005
output:
revealjs::revealjs_presentation:
md_extensions: +fenced_code_attributes
---
<style>
pre.smallCode {
width: 360px; /* Change the width of the chunk */
height: 360px; /* Change the height of the chunk */
font-size: 0.4em; /* Change the font-size */
background-color: lightgrey; /* Change background color */
}
</style>
```{r, include=FALSE}
knitr::knit_hooks$set(source = function(x, options) {
return(paste0(
"```{.r",
ifelse(is.null(options$class),
"",
paste0(" .", gsub(" ", " .", options$class))
),
"}\n",
x,
"\n```"
))
})
```
# Customized Code Chunks
## Example
<!-- Here we use the option tidy=TRUE with a cutoff after 40 characters -->
```{r, class = 'smallCode', tidy=T, tidy.opts=list(width.cutoff=40)}
df <- data.frame(A = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
```
这是我们刚刚自定义的代码块的屏幕截图: