In xaringan, how to change the margin under flextable title?

Viewed 50

Let's say I have the following xaringan document:

---
title: "Test"
author: 
  - "me"
date: "2022-06-20"
output:
  xaringan::moon_reader:
    css: [default, ninjutsu]
    seal: false
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---
```{r table, tab.cap="Iris", echo=F, warning=F, message=F}
library(tidyverse)
library(flextable)

iris %>%
  head() %>%
  flextable() %>%
  theme_booktabs()
```

which renders like this:

enter image description here

Now I wish to change the spacing between the flextable title and the table itself. What should I do?

enter image description here

2 Answers

I have no idea where the settings to be changed are defined, but when changing them, the extra space disappears... It needs to be done in css and the properties to set to 0 are 'margin-block-start' and 'margin-block-end'.

---
title: "Test"
author: 
  - "me"
date: "2022-06-20"
output:
  xaringan::moon_reader:
    css: [default, ninjutsu]
    seal: false
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

```{css}
p {
  margin-block-start: 0px;
  margin-block-end: 0px;
}
```


```{r table, tab.cap="Iris", echo=F, warning=F, message=F}
library(tidyverse)
library(flextable)

iris %>%
  head() %>%
  flextable() %>%
  theme_booktabs()
```

My own additions to David Gohel's answer:

After editing margin-block-start and margin-block-end, there will still be some gaps left in between the caption and the table, like this:

table with caption margin

My guess from checking the code is that the HTML rendering of flextable requires tabwid.css, which can be located by entering system.file(package="flextable", "web_1.1.0", "tabwid.css") in R console.

In tabwid.css, it reads:

.tabwid table{
  border-spacing:0px !important;
  border-collapse:collapse;
  line-height:1;
  margin-left:auto;
  margin-right:auto;
  border-width: 0;
  display: table;
  margin-top: 1.275em;
  margin-bottom: 1.275em;
  border-color: transparent;
}

The margin-top and margin-bottom values are the reason of the remaining gap between caption and table. I edited these values in element inspector to see the effect:

table with caption margin, inspected in browser

after changing margin values in inspector, the gap between caption and table is gone

As far as my very limited knowledge goes, there's no way of changing the margin-top and margin-bottom of .tabwid table{} other than editing tabwid.css in the package itself. (adding a {css} block in rmarkdown script doesn't work)

Then again, for the sake of development simplicity and aesthetics, it might be a horrible idea to touch that file on my own.

Related