14

I would like to make the font size of all figure captions in my R Markdown document smaller. The final output is HTML and I'm working in R Studio. To load the picture, I use the include_graphics function from knitr, because I've been told it's the best way (see here). My .Rmd file is:

---
title: "ppp"
author: "ppp"
date: "July 4, 2017"
output: 
  html_document: 
    fig_caption: yes
---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
```


```{r foo, fig.cap="$f_{p}$ as a function of $g$ for various values of $r=\\frac{\\rho_{w}}{\\rho_{a}}$"}
# All defaults
include_graphics("download.jpg")
``` 

This is regular text.

The corresponding output is: enter image description here

As you can see, the caption font size and the regular text font size are exactly the same, which doesn't look that nice. How can I solve this problem?

M--
  • 25,431
  • 8
  • 61
  • 93
DeltaIV
  • 4,773
  • 12
  • 39
  • 86

2 Answers2

21

Just add the following CSS to your Rmd document (anywhere below the YAML header):

<style>
p.caption {
  font-size: 0.6em;
}
</style>

What are we doing here:

If you mark the caption in your browser and inspect that element (Chrome: right-click -> Inspect) you can see that the caption is actually a HTML paragraph with a class named caption:

<p class="caption"> ... </p>

With the above CSS code we change the font-size of exactly those elements (and only those) to 60% of the default size.


enter image description here

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • Would +2 your answer for the Doge meme just a question, where do I put this CSS in my Rmd doc? In the YAML header? – DeltaIV Jul 11 '17 at 06:41
  • 1
    No, you put it somewhere below the YAML. I prefer to put CSS or JavaScript Code right below the YAML. – Martin Schmelzer Jul 11 '17 at 07:35
  • 1
    It works! Thanks a lot :) ps I had a look at your GitHub and learned this nifty trick: instead than `date: "July 4, 2017"`, `date: "\`r Sys.Date()\`"` is much better! – DeltaIV Jul 11 '17 at 10:22
  • If you use Bookdown or Blogdown, you can add the same CSS to your main CSS file. (without the – Richard Sprague Dec 03 '19 at 17:47
0

To embed it within the RMD documents, use this chunk:

```{css, echo=FALSE}
p {
  font-size: 32px;
}
```

How this looks within the whole RMD file:

---
title: "ppp"
author: "ppp"
date: "July 4, 2017"
output: 
  html_document: 
    fig_caption: yes
---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
```


```{css, echo=FALSE}
p {
  font-size: 32px;
}
```


```{r foo, fig.cap="$f_{p}$ as a function of $g$ for various values of $r=\\frac{\\rho_{w}}{\\rho_{a}}$"}
# All defaults
include_graphics("download.jpg")
``` 

This is regular text.

maycca
  • 3,848
  • 5
  • 36
  • 67