【问题标题】:R markdown: how to change style with internal css?R markdown:如何使用内部 css 更改样式?
【发布时间】:2015-12-01 14:15:10
【问题描述】:

我知道如何使用自定义 css 文件更改 R markdown 样式。但是,当更改较小时,我更喜欢内部甚至内联 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;
}

【问题讨论】:

    标签: css r markdown knitr


    【解决方案1】:

    Markdown 接受原始 HTML 并通过原样传递,因此将“样式化”元素定义为 HTML:

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

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

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

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

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

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

    ---
    title: "test"
    output: 
        html_document
    ---
    
    <style>
        #header1 {
            color: red;
        }
    </style>
    
    ## Header 1 {#header1}
    But how to change style with internal css?
    

    【讨论】:

    • 除了为每个元素定义 css inline 外,还可以将 css 直接包含在 markdown 文件中,以便将其应用于所有元素 --- title: "test" output: html_document --- &lt;style&gt; #header1 { color: red; } &lt;/style&gt; ## Header 1 {#header1}
    【解决方案2】:

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

      ---
      title: "test"
      output: html_document
      ---
    
      ```{css, echo = FALSE}
    
      #header1 {
      color: red;
      }
    
      ```
    
      ## Header 1 {#header1}
    

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

    【讨论】:

      【解决方案3】:

      另一种 hacky 选项是在脚本中指定一个 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的头块中引用了mystyle.css这个文件。然后,我使用writeLines() 创建文件,并将其保存到使用con = ... 指定的文件中。

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

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

      【讨论】:

        猜你喜欢
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-07
        • 2018-05-02
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多