正如您所意识到的,您不应该增加.main-container 的宽度,而是增加图像的宽度。以下是实现它的一种方法:
---
title: "R Markdown Full-width Figures"
output: html_document
---
```{r out.extra='style="max-width:none; width:100vw; margin-left:calc(50% - 50vw);"', fig.width = 12, fig.height = 3, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
plot(pressure)
```
首先,您需要删除max-width: none; 的默认max-width 约束(由rmarkdown 施加)。然后将图像的宽度设置为100vw,即窗口的全宽。此时,您的图像在.main-container 内部仍然是左对齐的,即它的左侧与正文的其余元素对齐,因此您需要将图像向左移动,使其接触到左边距窗口,这就是margin-left: calc(50% - 50vw) 在上面所做的。你可以在一张纸上画一个方框来理解它。基本上,margin-left: 50% 意味着图像将首先向右移动其容器宽度的一半(即.main-container)。这意味着它的左侧位于容器的中心。由于容器以页面为中心,您需要将图像向左移动50vw(即窗口宽度的一半)。向左移动意味着给它一个负的左边距,因此-50vw。 calc() 函数动态计算实际像素数,因此您不必假设容器的宽度是固定的。
一旦你理解了margin-left这个技巧,你就可以使用其他可能的宽度,例如width: 90vw; margin-left: calc(50% - 45vw),它会给你一个宽度为90vw并在页面上居中的图像:
如果您不想内联 <img> 上的 CSS,您可以将代码块包装在带有类名的 fenced Div 中,这样您就可以重用为该类定义的 CSS。这是一个例子:
---
title: "R Markdown Full-width Figures"
output: html_document
---
```{css, echo=FALSE}
.fullwidth img {
max-width: none;
width: 100vw;
margin-left: calc(50% - 50vw);
}
```
## One plot
::: {.fullwidth}
```{r, fig.width = 12, fig.height = 3, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
plot(pressure)
```
:::
## Another plot
::: {.fullwidth}
```{r, fig.width = 12, fig.height = 5, device = "svg"}
par(mar = c(4, 4.5, 1, .5))
boxplot(mpg ~ gear, data = mtcars, horizontal = TRUE)
```
:::