问题
Below is the code I am using. Only problem is that both my tables are of same colour which is my second colour code (#ffff99). How can I keep the background of both tables different.
<style>
table {
background-color:#eff8e5;
}
</style>
``` {r}
kable(df1)
```
<style>
table {
background-color:#ffff99;
}
</style>
``` {r}
kable(df2)
```
回答1:
HTML/CSS is not rendered the way you implicitly assume. Your code would work as expected if the rendering followed a procedure like:
- set: "tables are green"
- output green table
- set: "tables are yellow"
- output yellow table
But this is not the case. What actually happens is:
- set: "all tables are green"
- output table 1
- (table 1 is green)
- set: "all tables are yellow"
- output table 2
- (table 1 and table 2 are yellow)
As a solution, you could use two different classes:
<style>
.lightgreen {
background-color:#eff8e5;
}
.yellow {
background-color:#ffff99;
}
</style>
(Optimally, class names should describe the reason why the class is used and not how the class currently looks like, but without further information "lightgreen" and "yellow" are the best names I came up with).
Now you need to tell kable
that the tables should get these classes assigned.
Option 1:
kable(df1, format = "html", table.attr = "class=\"lightgreen\"")
kable(df2, format = "html", table.attr = "class=\"yellow\"")
However, this strips most of the (probably desired) default table layout.
Option 2: Add a container around the tables and style tables in that container.
<style>
.lightgreen table {
background-color:#eff8e5;
}
.yellow table {
background-color:#ffff99;
}
</style>
<div class = "lightgreen">
```{r}
library(knitr)
df1 <- data.frame(a=1:10, b=2:11)
kable(df1)
```
</div>
<div class = "yellow">
```{r}
df2 <- data.frame(a=1:10, b=2:11)
kable(df2)
```
</div>
来源:https://stackoverflow.com/questions/34509219/how-to-colour-different-rmarkdown-kable-tables-in-different-colour