Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align table left in HTML output using R Markdown and Knitr

I am experimenting with Knitr/KableExtra in RStudio but cannot make my tables use the full width of the web browser or control the table alignment on the screen.

Below is an example of the code where as per the kable_styling documentation, I have tried force the table to align to the left of the screen but in the html output, the table is always centered. It sees that there is an invisible margin to the left that I can't use. The problem arises when I have a table with more fields....the large margin on the left remains, forcing the table to extend to the right of the screen and generate a horizontal scrollbar - very annoying and ugly.

Is there some way I can use the space on the left margin or force the table to align truly to the left?

Here is an example of the issue:

example

---
title: "Untitled"
author: "ME"
date: "2/4/2020"
output: html_document
---

```{r setup, include=FALSE}
library(kableExtra)

knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
x_html <- knitr::kable(head(mtcars), "html")
kable_styling(x_html, "striped", position = "left", font_size = 7)
```

like image 820
djme Avatar asked Dec 15 '25 15:12

djme


1 Answers

You need to tweak the default CSS theme. For example, to make the content display on 100% of the available width:


```{css}
.main-container {
    max-width: 100%;
}
```

There are other solutions but this one is probably the most easy:


---
title: "Untitled"
author: "ME"
date: "2/4/2020"
output: html_document
---

```{r setup, include=FALSE}
library(kableExtra)

knitr::opts_chunk$set(echo = TRUE)
```

```{css}
.main-container {
    max-width: 100%;
}
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
x_html <- knitr::kable(head(mtcars), "html")
kable_styling(x_html, "striped", position = "left", font_size = 7)
```

like image 89
David Gohel Avatar answered Dec 17 '25 11:12

David Gohel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!