Display name
Display name

Reputation: 4501

can't align rows with kableExtra `cell_spec()`

---
title: "Untitled"
output: html_document
---

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

```{r mtcars, warning=FALSE, message=FALSE, echo=FALSE, results='asis'}
library(tidyverse)
library(kableExtra)
kable(mtcars %>% 
        select(1:5) %>% 
        head(10) %>% 
        mutate(cyl = cell_spec(cyl, align = "r")), 
      "html", 
      escape = FALSE) %>% 
  kable_styling("striped", "hover", full_width = TRUE) %>%
  row_spec(c(1, 3), background = "yellow")
```

I follow the KableExtra guide to align cells using the cell_spec() function. I am trying to right align my cyl column. But notice the column is not right aligned (image below).

What went wrong?

kableExtra align

Upvotes: 0

Views: 2815

Answers (1)

Hao
Hao

Reputation: 7856

Jason, the kable function itself has an align option. I think if you are not looking for any conditional alignment, you should just use that.

library(kableExtra)
library(tidyverse)
mtcars %>% 
  select(1:5) %>% 
  head(10) %>%
  kable(align = c("crcccc")) %>% 
  kable_styling("striped", "hover", full_width = TRUE) %>%
  row_spec(c(1, 3), background = "yellow")

For cell_spec itself, it seems like right now this align option for HTML just won't give you what you need. If you check the raw HTML generated by this approach, you will see ultimately, cell_spec puts your cell into a <span> tag. You can specify text_align there but that gets overrided by the text_align setting in <td>. I will see if I should fix this or add a warning note here in this section.

<td style="text-align:left;"> <span style="     text-align: right;">4</span> </td>

Upvotes: 2

Related Questions