7.5 Tables
Q: How to make the tables more compact, e.g, reduce the row height?
A: You can use CSS to adjust the table styles. For example, add the following CSS rules to your custom CSS file (e.g., custom.css):
/* Compact table styling */
.compact-table table {
line-height: 1.2;
font-size: 0.9em;
}
.compact-table th,
.compact-table td {
/* vertical padding: 2px; */
/* horizontal padding: 8px */
padding: 2px 8px !important;
}Then, in your slide, wrap your markdown table with a div that has the compact-table class:
.compact-table[
| Header 1 | Header 2 | Header 3 |
|----------|----------|----------|
| Row 1 | Data | More Data|
| Row 2 | Data | More Data|
]If your table is generated from R code, you can modify the HTML output to include the class:
```{r echo=FALSE, results='asis'}
tbl_html <- knitr::kable(df, format = "html") %>%
as.character()
tbl_html <- sub("<table", '<table class="compact-table"', tbl_html)
cat(tbl_html)
```Note that:
as.character()converts the HTML table to a character string so that you can manipulate it as text.sub("<table", '<table class="compact-table"', tbl_html)searches for the first occurrence of<tablein the HTML string; replaces it with<table class="compact-table". This adds the class.compact-tableto the<table>tag, which allows you to style it using your CSS (like the.compact-tableCSS you showed earlier).cat(tbl_html)prints the modified HTML string to the slide.catis required here because you want to output the HTML directly, not as a character string.
Q: I want to add more horizontal spacing in table cells, but keep narrow left spacing for the 1st column.
A: Add the following CSS rules to your custom CSS file (e.g., custom.css):
/* Add horizontal spacing in table cells, but keep narrow left spacing for the 1st column */
.fit-comp-table td,
.fit-comp-table th {
padding: 4px 18px !important; /* increase horizontal padding */
}
.fit-comp-table th:first-child,
.fit-comp-table td:first-child {
padding-left: 4px !important; /* tight left spacing for 1st column */
}Then, in your slide, wrap your table with a div that has the fit-comp-table class:
```{r echo=FALSE, results='asis'}
fit_comp <- tibble(
Metric = c("Residual Std. Error: CAPM", "Residual Std. Error: FF-3"),
AAPL = c("0.092", "0.089"),
SLAB = c("0.116", "0.107"),
KO = c("0.046", "0.044")
)
tbl_html <- fit_comp %>%
knitr::kable(format = "html", align = c("l", "c", "c", "c")) %>%
as.character()
tbl_html <- sub("<table", '<table class="fit-comp-table"', tbl_html)
cat(tbl_html)
```