Search code examples
r-markdownpandocquarto

How to place *multiple* code chunks side by side in Quarto -> HTML?


How can I place multiple code chunks side-by-side in Quarto -> HTML? I've seen this answer, which is great, but it accounts for just 2 code chunks. Is there a way to place up to 4-5 code chunks side-by-side, possibly using .column-screen-inset, to take advantage of the entire screen width?

I know a way to get exactly what I want, but it has two caveats (which are essentially one):

  1. It works for images
  2. It relies on knitr::include_graphics()

Thus, if I do:

my_file.qmd

---
title: "quarto-page-side-by-side"
---

```{r}
#| eval: true
#| echo: false
#| layout-ncol: 4
#| column: screen-inset

knitr::include_graphics("media/a.jpg")
knitr::include_graphics("media/b.jpg")
knitr::include_graphics("media/c.jpg")
knitr::include_graphics("media/d.jpg")
```

I get this nice page layout with 4 images, side-by-side, that get resized as I change the window size. What's more, if we keep narrowing the window, ultimately the images will be stacked one on top of the other.

Is there a way to achieve this functionality or similar, but with code chunks instead of images?


Solution

  • You can try this using some CSS.

    ---
    title: "quarto-page-side-by-side"
    ---
    
    ```{css, echo=FALSE, eval=TRUE}
    .multiple .column {
      width: 15%;
      margin: 5px;
    }
    
    .multiple .columns {
      display: flex;
    }
    
    @media (max-width: 767px) {
      .multiple .column {
        width: auto;
      }
    
     .multiple .columns {
       display: flex;
       flex-direction: column;
      }
    }
    ```
    
    ::::: { .multiple}
    
    :::: {.columns .column-screen-inset}
    
    ::: column
    ```{r}
    print("This is the 1st code chunk")
    ```
    :::
    
    ::: column
    ```{r}
    print("This is the 2nd code chunk")
    ```
    :::
    
    ::: column
    ```{r}
    print("This is the 3rd code chunk")
    ```
    :::
    
    ::: column
    ```{r}
    print("This is the 4th code chunk")
    ```
    :::
    
    ::: column
    ```{r}
    print("This is the 5th code chunk")
    ```
    :::
    
    ::::
    :::::
    

    five code chunks placed side by side


    If you want to add more chunks side by side, just decrease the value of the width property within the .multiple .column selector.