R markdown:如何使用内部 css 更改样式?

R markdown: how to change style with internal css?

我知道如何使用自定义 css 文件更改 R markdown 样式。但是,当更改较小时,我更喜欢 internal 甚至 inline css,以省去管理两个文件的麻烦。我用谷歌搜索并没有找到解决方案。下面是一个使用外部 css 文件更改样式的简单示例。有没有办法使用内部或内联 css?

R 降价文件:

---
title: "test"
output: 
    html_document:
        css: test.css
---

## Header 1 {#header1}
But how to change style with internal css?

test.css 文件:

#header1 {
color: red;
}

Markdown 接受原始 HTML 并原封不动地传递它,因此将 "styled" 元素定义为 HTML:

<h2 style="color: red;">Header 1</h2>

当然,有些工具实际上不允许原始 HTML 通过(出于安全原因或因为最终输出不是 HTML),因此您的里程可能会有所不同。

根据您使用的 Markdown 实现,您可以在属性列表中定义样式(如果它支持任意键):

## Header 1 {style="color: red;"}

但是,这是最不可能奏效的。

请记住,HTML <style> 标签不需要在文档中 <head> 才能工作。如果可以使用原始 HTML,则可以在文档正文中包含一个 <style> 元素(正如@user5219763 在评论中指出的那样):

---
title: "test"
output: 
    html_document
---

<style>
    #header1 {
        color: red;
    }
</style>

## Header 1 {#header1}
But how to change style with internal css?

另一个有点古怪的选项是在脚本中指定一个 css 文件,然后在第一个块中创建它。

例如.Rmd 文件的前 18 行:

  ---
  title: "Something Important"
  output: 
    html_document:
      css: mystyle.css
  ---


  ```{r b, echo=F}
  writeLines("td, th { padding : 6px } 
             th { background-color : coral ; 
                  color : white; 
                  border : 1px solid white; } 
             td { color : black ; 
                  border : 1px solid skyblue }
             h1, h2, h3, h4, h5, p { font-family: consolas; ",
             con = "mystyle.css")
  ```

上面我先在markdown的header块中引用了文件mystyle.css。然后,我使用 writeLines() 创建文件,并将其保存到 con = ....

指定的文件中

就我个人而言,如果它是一次性 R 脚本,我认为最好的选择是将代码放在一些 <script></script> 标记之间。

但是,如果您确实想要创建一个外部文件,但不想编辑一个单独的文件,上述方法提供了一种解决方法。就是觉得奇怪。

如果您不想创建外部 .css 文件,但想定义多种样式并且希望让您的代码不那么拥挤,另一种可能性是使用 css R 降价开头的块:

  ---
  title: "test"
  output: html_document
  ---

  ```{css, echo = FALSE}

  #header1 {
  color: red;
  }

  ```

  ## Header 1 {#header1}

css 块中,您可以控制多种样式,就像在外部 .css 文件中一样。