With R `bookdown::gitbook` can I center figures but not the captions?

Viewed 218

I am trying to replicate part of a textbook using bookdown::gitbook:. To match it, I would like to have my figures centered but the captions left aligned. When I specify fig.align="center" it also centers the caption text. The captions are crazy long and look bad centered. Is there a way to specify that I would like to center the images but left align the caption's text? Here is what I have:

---
title: "Notes for An Introduction to Statistical Learning with Applications in R, Second Edition"
author: "me"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::gitbook: 
    config: 
      toc:
        collapse: false
    fig_caption: true
    number_sections: true
    global_numbering: true

description: "Notes for ISLR2"
---

Chapter 1

words ... more words .... yet more works...

```{r fig1-3, cache=FALSE, echo=FALSE, fig.align="center", fig.cap="_We fit a quadratic discriminant analysis model to the subset of the `Smarket` data corresponding to the 2001–2004 time period, and predicted the probability of a stock market decrease using the 2005 data. On average, the predicted probability of decrease is higher for the days in which the market does decrease. Based on these results, we are able to correctly predict the direction of movement in the market 60% of the time._"}

knitr::include_graphics("./images/fig1_2.jpg", error = FALSE)

```
2 Answers

Thanks again @all-downhill-from-here. I got it to work by adding a .css file. I have no idea why by the r chuck with "asis" or a css chunk did not work.

I got the alignment and other details to work like this:

p.caption {
  text-align: left; 
  color: gray; 
  font-style: italic; 
}

The knitr output produces an html element with class='caption', so we can add a small bit of custom css code to make it left-align (one of my favourite tricks in html output!):

```{r echo=F, results='asis'}
cat("<style>.caption{text-align:left;}</style>")
```
Related