使用CSS的Knitr风格表格

27

我相信我可能忽略了一些显而易见的东西,但我想用自定义的css样式来设计我的表格和 kable

你可以在这里找到我 RMDCSS 文件的要点。

我的目标是利用我在这里找到的表格CSS示例。

当我运行报告时,我的表格看起来像这样:

enter image description here

但是根据上面的CSS示例,它应该看起来像下面的图片。

enter image description here

我的问题是:我错过了什么,或者这种程度的样式化对于 RMarkdown 不可能实现。

以下是我的RMD文件:

---
title: "Test Table CSS"
output: 
  html_document:
    theme: NULL
    style: flat-table.css
---

I want to be able to style my tables with CSS. From the looks of it, I should be able to do that 
through the use of `CSS` and `knitr:kable`.  


```{r setup, echo=FALSE}
data(mtcars)
mt_head = head(mtcars[, 1:5])
```

I want to be able to style my table just like one found [here](http://codepen.io/njessen/pen/naLCv)


```{r echo=FALSE, results='asis'}
library(knitr)
kable(mt_head, "html", table.attr='class="flat-table"')
```
3个回答

31

如果您拿到了.Rmd文件以及下面修改过的CSS文件,您可以通过以下方式获得您想要的结果:

knitr::knit2html('my-report.RMD', stylesheet = 'flat-table.css')

以下是结果:在此输入图片描述

这里更新了flat-table.css文件:

.flat-table {
  display: block;
  font-family: sans-serif;
  -webkit-font-smoothing: antialiased;
  font-size: 115%;
  overflow: auto;
  width: auto;
}
  th {
    background-color: rgb(112, 196, 105);
    color: white;
    font-weight: normal;
    padding: 20px 30px;
    text-align: center;
  }
  td {
    background-color: rgb(238, 238, 238);
    color: rgb(111, 111, 111);
    padding: 20px 30px;
  }

谢谢。我重新开始了,采用了您修改后的CSS(这显然是我的疏忽,对吧),并创建了一个新的Github仓库(链接在此:https://github.com/Btibert3/so-knitr-tables/tree/master)。新的仓库可以正常工作。谢谢! - Btibert3
5
在目前的 Rstudio/pandoc/knitr 版本中,你可以在 YAML 中指定 CSS 样式:output: html_document: css: flat-table.css - patrickmdnet
Thomas,谢谢你的回答!我只是想知道是否有意义添加一个有关@patrickmdnet提议的YAML css的条款。 - akhmed
@akhmed 可以随意编辑答案。我没有尝试过这个工作流程,所以我不知道正确的表示方法是什么。 - Thomas

1
如果你只需要进行少量的自定义,可以考虑将CSS直接包含在RMarkdown文件中(包含CSS)。只要将其封装在<style> </style>中,Markdown就会直接传递CSS。以下是一个完整的示例:
---
output: html_document
---

# Test Project

<style>
  .flat-table {
    display: block;
    font-family: sans-serif;
    -webkit-font-smoothing: antialiased;
    font-size: 115%;
    overflow: auto;
    width: auto;
  }
  thead {
    background-color: rgb(112, 196, 105);
    color: white;
    font-weight: normal;
    padding: 20px 30px;
    text-align: center;
  }
  tbody {
    background-color: rgb(238, 238, 238);
    color: rgb(111, 111, 111);
    padding: 20px 30px;
  }
</style>



```{r}
knitr::kable(mtcars[1:5, 1:5])
```

enter image description here

高级格式化

这个指南提供了关于CSS表格样式的大量有用信息。你可以用几行CSS代码实现一些很酷的效果。例如,你可以在鼠标悬停时突出显示表格的行:

tbody tr:hover {
  background: yellow;
}     

enter image description here

请注意,许多表格样式使用某种形式的JavaScript来使格式化工作,并且可能会进行影响文档其余部分的更改。最好使用和标签。

0

请查看自定义块

有一种Markdown语法可以添加属性。

::: {#id..class}
```{r showdata}
knitr::kable(yourtable)
```
:::

例如

::: {#table .table .table-bordered}
```{r showdata}
knitr::kable(cars)
```
:::

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接