简体   繁体   English

将自定义 CSS 标签添加到 RMarkdown html 文档

[英]Adding custom CSS tags to an RMarkdown html document

I have an RMarkdown document outputting to HTML of the same form as the below example.我有一个 RMarkdown 文档输出到与以下示例相同形式的 HTML。 What do I add where to apply unique CSS ids or classes to each plot output?我应该添加什么来将唯一的 CSS id 或类应用于每个绘图输出?

---
title: "RMarkdown"
author: "Me"
date: "Friday, March 27, 2015"
output:
  html_document:
    theme: null
    css: style.css
---

```{r plot1, echo=FALSE, warning=FALSE, message=FALSE}
library(ggplot2)
x <- ggplot(some_r_code)
print(x)
```

```{r plot2, echo=FALSE, warning=FALSE, message=FALSE}
y <- ggplot(some_more_r_code)
print(y)
```

I've read the info page at http://rmarkdown.rstudio.com/html_document_format.html that went a ways to answering this question but didn't get me there.我已经阅读了http://rmarkdown.rstudio.com/html_document_format.html上的信息页面,该页面提供了回答这个问题的方法,但没有让我到达那里。 I have a similar question referencing the material in that page in it's comment section, and would appreciate an answer on either.我有一个类似的问题,在它的评论部分引用了该页面中的材料,并希望得到任何答案。

Thanks!谢谢!

You can tell knitr (which is used under the hood) with results="asis" to embed a chunk's output directly into the html.您可以使用results="asis"告诉 knitr(在后台使用)将块的输出直接嵌入到 html 中。 Within the chunk you can use cat to simply write a style tag including your css definitions:在块中,您可以使用cat简单地编写一个样式标签,包括您的 css 定义:

```{r results="asis"}
cat("
<style>
h1 {
   color: red;
}
</style>
")
```

See http://yihui.name/knitr/options/#chunk_options for details.详见http://yihui.name/knitr/options/#chunk_options

Here are some additional ways of achieving custom css in RMarkdown以下是在 RMarkdown 中实现自定义 css 的一些其他方法

  • Add css between <style> and </style> tags in the regular body of the RMarkdown (ie not in R code area), like so:在 RMarkdown 的常规正文中的<style></style>标签之间添加 css(即不在 R 代码区域中),如下所示:
<style>
.pad {
    padding-top: 200px; 
}
</style>

# This heading will be padded {.pad}

Open the resultant HTML in a browser with a Developer Tools option and look at the generated HTML.使用开发人员工具选项在浏览器中打开生成的 HTML 并查看生成的 HTML。 Then apply you styling to the appropriate tags/classes.然后将您的样式应用到适当的标签/类。 For example, put the following into style.css , knit the file and you should see a red border on the plots:例如,将以下内容放入style.css ,编织文件,您应该会在绘图上看到一个红色边框:

img {
  background-color: red;
  padding: 2px;
  border: 1px solid red;
  border-radius: 3px;
  margin: 0 5px;
  max-width: 100%;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM