4  Styling

In this chapter, we’re styling our tables. This means we’re going to customize their theme. To do so, let us bring back our last table from Chapter 1. This is the table we’ll customize.

In this chapter, we don’t really need the code of that table. So, I will only reprint the code in a folded section. Just know that the table is saved in a variable penguins_table.

Code
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0          ✔ purrr   0.3.5     
## ✔ tibble  3.1.8          ✔ dplyr   1.0.10    
## ✔ tidyr   1.2.1          ✔ stringr 1.4.1.9000
## ✔ readr   2.1.3          ✔ forcats 0.5.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(gt)
penguins <- palmerpenguins::penguins |> filter(!is.na(sex))
penguin_counts <- penguins |> 
  mutate(year = as.character(year)) |> 
  group_by(species, island, sex, year) |> 
  summarise(n = n(), .groups = 'drop')
penguin_counts_wider <- penguin_counts |> 
  pivot_wider(
    names_from = c(species, sex),
    values_from = n
  ) |> 
  # Make missing numbers (NAs) into zero
  mutate(across(.cols = -(1:2), .fns = ~replace_na(., replace = 0))) |> 
  arrange(island, year) 

actual_colnames <- colnames(penguin_counts_wider)
desired_colnames <- actual_colnames |> 
  str_remove('(Adelie|Gentoo|Chinstrap)_') |> 
  str_to_title()
names(desired_colnames) <- actual_colnames


penguins_table <- penguin_counts_wider |> 
  mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |> 
  mutate(
    island = as.character(island), 
    year = as.numeric(year),
    island = paste0('Island: ', island)
  ) |> 
  gt(groupname_col = 'island', rowname_col = 'year') |> 
  cols_label(.list = desired_colnames) |> 
  tab_spanner(
    label = md('**Adelie**'),
    columns = 3:4
  ) |> 
  tab_spanner(
    label = md('**Chinstrap**'),
    columns = c('Chinstrap_female', 'Chinstrap_male')
  ) |> 
  tab_spanner(
    label =  md('**Gentoo**'),
    columns = contains('Gentoo')
  ) |> 
  tab_header(
    title = 'Penguins in the Palmer Archipelago',
    subtitle = 'Data is courtesy of the {palmerpenguins} R package'
  ) |> 
  sub_missing(missing_text = '-') |>
  summary_rows(
    groups = TRUE,
    fns = list(
      'Maximum' = ~max(.),
      'Total' = ~sum(.) 
    ),
    formatter = fmt_number,
    decimals = 0,
    missing_text = '-'
  )  |> 
  tab_options(
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  opt_stylize(style = 6, color = 'gray')
penguins_table
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

4.1 Theming

The easiest way to style a table is to apply a pre-installed theme via opt_stylize(). We’ve already done that in the first chapter because it’s really easy to do. But there’s nothing stopping us from overwritting the theme. Just apply another opt_stylize() layer to the table.

penguins_table |> 
  opt_stylize(style = 6, color = 'pink')
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

4.1.1 Tab options

Next, we can tweak our table’s appearance with tab_options(). It’s basically the analogue of theme() in {ggplot2}. In Chapter 1, we’ve already used tab_options() to apply three small changes. Once again, there’s no harm in applying another layer of the same stuff.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

But let’s change a couple of things. Warning: These changes may or may not “improve” the table. We’ll just apply stuff to learn what’s going on. We can worry about aesthetics later.

We’ll start by styling the heading a little bit. All of the arguments in tab_options() that target the header start with heading.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  # Change header theme
  tab_options(
    heading.align = 'left',
    heading.background.color = 'darkgreen',
    heading.title.font.size = px(20)
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

Next, let us attack our column labels. We’ll do two things:

  1. Change the background color (simple)
  2. Remove the bottom border line (A bit tricky. You’ll see why in a sec.)

To achieve the latter thing, you need to change border-style. The most common are solid, dashed, dotted and none. Guess which one we’re choosing.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  # Change header theme
  tab_options(
    heading.align = 'left',
    heading.background.color = 'darkgreen',
    heading.title.font.size = px(20)
  ) |> 
  tab_options(
    column_labels.background.color = 'yellow',
    column_labels.border.bottom.style = 'none'
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

The effect of the color change is clearly visible. But what’s that? There is still a line below the column labels. The reason for this is simple: There is no border below the column_labels area anymore. But there is still a border above the table_body and the row_group. Yes, that’s right. You can only remove one line at the cost of three1.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  # Change header theme
  tab_options(
    heading.align = 'left',
    heading.background.color = 'darkgreen',
    heading.title.font.size = px(20)
  ) |> 
  tab_options(
    column_labels.background.color = 'yellow',
    column_labels.border.bottom.style = 'none',
    row_group.border.top.style = 'none',
    table_body.border.top.style = 'none'
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

So how do you find out which areas might affect whatever it is that you want to style? Lucky for us, the gt docs have a neat image that shows you the areas of a {gt} table.

Figure 4.1: This figure is taken straight form the gt docs. I didn’t find a license for this image. But I hope it’s cool if I use it. Please let me know if not.

There’s one more way to find out what border you need to overwrite and we’ll talk about it in Section 4.2. For now, let me show you how you can target even more specific parts of your table.

4.1.2 Cell styling

Imagine that you want to turn the Chinstrap column spanner blue (for whatever reason). You have seen that you can target only all column labels and all column spanners with tab_options(). For very specific wishes (like this one), there’s tab_style().

This function has two arguments: locations and style. Does this remind you of something? That’s right, it’s very similar to text_transform() which you learned in Chapter 2. But instead of applying a text transformation function to a cell, we apply a style.

Now, to specify locations and style we have two sets of helper functions. The location helpers translate more or less to the areas that you see in Figure 4.1.

Location helpers

  • cells_body()
  • cells_column_labels()
  • cells_column_spanners()
  • cells_footnotes()
  • cells_grand_summary()
  • cells_row_groups()
  • cells_stub()
  • cells_stub_grand_summary()
  • cells_stub_summary()
  • cells_stubhead()
  • cells_summary()
  • cells_title()

Style helpers

  • cell_borders()
  • cell_fill()
  • cell_text()

Applying these helpers is pretty straightforward. Just use them for either locations or style in tab_style(). For example, we can use cells_column_spanners() to target all column spanners. And with cell_fill() we can turn them blue.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  # Change header theme
  tab_options(
    heading.align = 'left',
    heading.background.color = 'darkgreen',
    heading.title.font.size = px(20)
  ) |> 
  tab_options(
    column_labels.background.color = 'yellow',
    column_labels.border.bottom.style = 'none',
    row_group.border.top.style = 'none',
    table_body.border.top.style = 'none'
  ) |> 
  tab_style(
    locations = cells_column_spanners(),
    style = cell_fill(color = 'dodgerblue')
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

Another cool way to target cells is tab_style_body(). Basically, it is a combination of fmt() from Chapter 3 and tab_style(). So, you can apply a style to table cells that either match a regex, correspond to a specific value or fulfill criteria according to your own custom function. Here’s one example of that.

penguins_table |> 
  tab_options(
    # These were the ones we applied in the first chapter
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  # Change header theme
  tab_options(
    heading.align = 'left',
    heading.background.color = 'darkgreen',
    heading.title.font.size = px(20)
  ) |> 
  tab_options(
    column_labels.background.color = 'yellow',
    column_labels.border.bottom.style = 'none',
    row_group.border.top.style = 'none',
    table_body.border.top.style = 'none'
  ) |> 
  tab_style(
    locations = cells_column_spanners(),
    style = cell_fill(color = 'dodgerblue')
  ) |> 
  tab_style_body(
    fn = function(x) between(x, 5, 10),
    style = cell_text(color = 'red', weight = 'bold')
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

Unfortunately, this function works only on cells in the body. Thus we have to find some other way to target the Chinstrap column spanner. To make this work, we have to assign an ID to the column spanner. Then, we can target that ID within cells_column_spanners(). Here’s a minimal example of how that works.

exibble |> 
  select(1:4) |> 
  gt() |> 
  opt_stylize(style = 3) |> 
  fmt_number(columns = 'num') |> 
  tab_spanner(
    columns = 1:2, 
    label = 'A column spanner', 
    id = 'spannerA' ## That's the ID we can target
  ) |> 
  tab_spanner(
    columns = 3:4, 
    label = 'Another column spanner', 
    id = 'spannerB' ## That's the ID we can target
  )  |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'spannerA'),
    style = cell_fill(color = 'darkgreen')
  ) |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'spannerB'),
    style = cell_fill(color = 'darkgreen', alpha = 0.5)
  )
A column spanner Another column spanner
num char fctr date
0.11 apricot one 2015-01-15
2.22 banana two 2015-02-15
33.33 coconut three 2015-03-15
444.40 durian four 2015-04-15
5,550.00 NA five 2015-05-15
NA fig six 2015-06-15
777,000.00 grapefruit seven NA
8,880,000.00 honeydew eight 2015-08-15

Applying this logic to our penguins table is straightforward. But you will have to copy the whole table code and insert an ID in the initial gt() layer. I think you get the idea. So here’s only the result (unfold for full code).

Code
penguin_counts_wider |> 
  mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |> 
  mutate(
    island = as.character(island), 
    year = as.numeric(year),
    island = paste0('Island: ', island)
  ) |> 
  gt(groupname_col = 'island', rowname_col = 'year') |> 
  cols_label(.list = desired_colnames) |> 
  tab_spanner(
    label = md('**Adelie**'),
    columns = 3:4
  ) |> 
  tab_spanner(
    label = md('**Chinstrap**'),
    columns = c('Chinstrap_female', 'Chinstrap_male'),
    id = 'chinstrap'
  ) |> 
  tab_spanner(
    label =  md('**Gentoo**'),
    columns = contains('Gentoo')
  ) |> 
  tab_header(
    title = 'Penguins in the Palmer Archipelago',
    subtitle = 'Data is courtesy of the {palmerpenguins} R package'
  ) |> 
  sub_missing(missing_text = '-') |>
  summary_rows(
    groups = TRUE,
    fns = list(
      'Maximum' = ~max(.),
      'Total' = ~sum(.) 
    ),
    formatter = fmt_number,
    decimals = 0,
    missing_text = '-'
  )  |> 
  tab_options(
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  opt_stylize(style = 6, color = 'gray') |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'chinstrap'),
    style = cell_fill(color = 'dodgerblue')
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

Notice that the grey border at the bottom of the Chinstrap column spanner looks kind of ugly. So, why not remove it? This is a great exercise of applying multiple styles. This is done by using multiple style helpers and collecting them in a list. The same works with location helpers. Here’s a small example again.

exibble |> 
  select(1:4) |> 
  gt() |> 
  opt_stylize(style = 3) |> 
  fmt_number(columns = 'num') |> 
  tab_spanner(
    columns = 1:2, 
    label = 'A column spanner', 
    id = 'spannerA'
  ) |> 
  tab_spanner(
    columns = 3:4, 
    label = 'Another column spanner', 
    id = 'spannerB'
  )  |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'spannerA'),
    style = cell_fill(color = 'darkgreen')
  ) |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'spannerB'),
    style = cell_fill(color = 'darkgreen', alpha = 0.5)
  ) |> 
  tab_style(
    locations = list(
      cells_column_labels(),
      cells_body(
        columns = c('char', 'date'), rows = c(3, 5, 8)
      )
    ),
    style = list(
      cell_fill(color = 'firebrick4'),
      cell_text(color = 'white', size = 14, weight = 'bold'),
      cell_borders(
        sides = c('left', 'right'), 
        color = 'green', 
        weight = px(3)
      )
    )
  )
A column spanner Another column spanner
num char fctr date
0.11 apricot one 2015-01-15
2.22 banana two 2015-02-15
33.33 coconut three 2015-03-15
444.40 durian four 2015-04-15
5,550.00 NA five 2015-05-15
NA fig six 2015-06-15
777,000.00 grapefruit seven NA
8,880,000.00 honeydew eight 2015-08-15

Now, applying the same logic to our Chinstrap column spanner should be easy, right? It is. But unfortunately, it didn’t help. Have a look for yourself. The border is still there.

Code
penguin_counts_wider |> 
  mutate(across(.cols = -(1:2), ~if_else(. == 0, NA_integer_, .))) |> 
  mutate(
    island = as.character(island), 
    year = as.numeric(year),
    island = paste0('Island: ', island)
  ) |> 
  gt(groupname_col = 'island', rowname_col = 'year') |> 
  cols_label(.list = desired_colnames) |> 
  tab_spanner(
    label = md('**Adelie**'),
    columns = 3:4
  ) |> 
  tab_spanner(
    label = md('**Chinstrap**'),
    columns = c('Chinstrap_female', 'Chinstrap_male'),
    id = 'chinstrap'
  ) |> 
  tab_spanner(
    label =  md('**Gentoo**'),
    columns = contains('Gentoo')
  ) |> 
  tab_header(
    title = 'Penguins in the Palmer Archipelago',
    subtitle = 'Data is courtesy of the {palmerpenguins} R package'
  ) |> 
  sub_missing(missing_text = '-') |>
  summary_rows(
    groups = TRUE,
    fns = list(
      'Maximum' = ~max(.),
      'Total' = ~sum(.) 
    ),
    formatter = fmt_number,
    decimals = 0,
    missing_text = '-'
  )  |> 
  tab_options(
    data_row.padding = px(2),
    summary_row.padding = px(3), # A bit more padding for summaries
    row_group.padding = px(4)    # And even more for our groups
  ) |> 
  opt_stylize(style = 6, color = 'gray') |> 
  tab_style(
    locations = cells_column_spanners(spanners = 'chinstrap'),
    style = list(
      cell_fill(color = 'dodgerblue'),
      cell_borders(style = 'hidden')
    )
  )
Penguins in the Palmer Archipelago
Data is courtesy of the {palmerpenguins} R package
Adelie Chinstrap Gentoo
Female Male Female Male Female Male
Island: Biscoe
2007 5 5 - - 16 17
2008 9 9 - - 22 23
2009 8 8 - - 20 21
Maximum 9 9 - - 22 23
Total 22 22 - - 58 61
Island: Dream
2007 9 10 13 13 - -
2008 8 8 9 9 - -
2009 10 10 12 12 - -
Maximum 10 10 13 13 - -
Total 27 28 34 34 - -
Island: Torgersen
2007 8 7 - - - -
2008 8 8 - - - -
2009 8 8 - - - -
Maximum 8 8 - - - -
Total 24 23 - - - -

The reason why this is happening is simple. It’s a known bug. But that’s not a problem. Actually, that’s a great motivation for our next part.

Whenever styling does not work as expected, {gt} allows you to sneak behind the HTML/CSS curtain. Then, you can manually apply whatever it is you want to apply.

I know that this may sound daunting but it’s actually quite manageable. I’ve learned most of what I know about HTML/CSS from styling my Quarto blog. And most of that happened via copy-and-paste. With a little bit of effort, you can do the same.

4.2 Custom CSS

Let’s do a HTML/CSS quick tour. First, let us start with something you’re already familiar with. You probably know that Markdown converts **blabla** to blabla, i.e. bold text. This means that with the right decoration, you can turn blabla into bold non-sense.

4.2.1 Tags and their styling

The idea is the same for HTML/CSS. With the right decoration, you can transform any text into something else. The cool thing is that with HTML/CSS you can do more than “just” bold text. You have way more options to transform your text.

Unfortunately, this power comes with a more verbose notation. For example, for bold inline text you could wrap blabla into <span style="font-weight:bold;">...</span>. In this case, <span>...</span> is just the tag to use inline text. This is not a particularly sexy thing to write. But it gives you the power to change more than just the font-weight inside the span tags.

You could add styles as you see fit. For example, you continue the list within style= by adding. color:blue;, font-family:Merriweather;….and so on.

Of course, there are not only <span> tags. For example, there’s <p> for paragraphs, <a> for hyperlinks and <div> for sections aka divisions. In our case there’s one more important tag that {gt} uses: <table>.

4.2.2 Classes and IDs

Just like your Markdown documents, websites are really just decorated texts. Every little tweak on a website can be accomplished by adding the right instruction into style=.

Now, comes the good part. You don’t have to repeat your style instructions all the time. You can recycle your styles. That’s what CSS classes do.

Let’s imagine that we want to recycle our previous style that used color:blue;, font-family:Merriweather; and font-weight:bold;. We can define a CSS class my-style that encodes that information as follows.

.my-style {
  color:blue;
  font-family:Merriweather;
  font-weight:bold;
}

Notice the . at the beginning. That’s the secret class symbol in CSS. And that’s also the only thing we need to know to overwrite the gt_table class to style our table like we want. The opt_css() layer will help us to get the CSS code into our website.

library(gt)
exibble |> 
  gt() |> 
  opt_css(
    '
    .gt_table {
      color:blue;
      font-family:Merriweather;
      font-weight:bold;
    }
    '
  )
num char fctr date time datetime currency row group
1.111e-01 apricot one 2015-01-15 13:35 2018-01-01 02:22 49.950 row_1 grp_a
2.222e+00 banana two 2015-02-15 14:40 2018-02-02 14:33 17.950 row_2 grp_a
3.333e+01 coconut three 2015-03-15 15:45 2018-03-03 03:44 1.390 row_3 grp_a
4.444e+02 durian four 2015-04-15 16:50 2018-04-04 15:55 65100.000 row_4 grp_a
5.550e+03 NA five 2015-05-15 17:55 2018-05-05 04:00 1325.810 row_5 grp_b
NA fig six 2015-06-15 NA 2018-06-06 16:11 13.255 row_6 grp_b
7.770e+05 grapefruit seven NA 19:10 2018-07-07 05:22 NA row_7 grp_b
8.880e+06 honeydew eight 2015-08-15 20:20 NA 0.440 row_8 grp_b

Unfortunately, this did not change anything. Why? Because {gt} is clever enough to encode its styling not only with a global CSS class like .gt_table but also with a unique ID for every table. This ensures that you cannot accidentally change the styling of a different {gt} table.

That’s why you can assign a custom ID for your table in gt() and target that ID in your CSS code. The secret symbol for IDs in CSS is #. Armed with that knowledge, let us try again.

library(gt)
exibble |> 
  gt(id = 'table_id') |> 
  opt_css(
    '
    #table_id .gt_table {
      color:blue;
      font-family:Merriweather;
      font-weight:bold;
    }
    '
  )
num char fctr date time datetime currency row group
1.111e-01 apricot one 2015-01-15 13:35 2018-01-01 02:22 49.950 row_1 grp_a
2.222e+00 banana two 2015-02-15 14:40 2018-02-02 14:33 17.950 row_2 grp_a
3.333e+01 coconut three 2015-03-15 15:45 2018-03-03 03:44 1.390 row_3 grp_a
4.444e+02 durian four 2015-04-15 16:50 2018-04-04 15:55 65100.000 row_4 grp_a
5.550e+03 NA five 2015-05-15 17:55 2018-05-05 04:00 1325.810 row_5 grp_b
NA fig six 2015-06-15 NA 2018-06-06 16:11 13.255 row_6 grp_b
7.770e+05 grapefruit seven NA 19:10 2018-07-07 05:22 NA row_7 grp_b
8.880e+06 honeydew eight 2015-08-15 20:20 NA 0.440 row_8 grp_b

Awesome. This worked. At least a bit. But the column labels remained the same. Here’s why.

The things that we want to change (color, font-family and font-weight of the column labels) are not styled in the .gt_table class. These are styled in .gt_col_heading.

Hence, you need to target that class as well. Maybe with different instructions.

exibble |> 
  gt(id = 'table_id') |> 
  opt_css(
    '
    #table_id .gt_table {
      color:blue;
      font-family:Merriweather;
      font-weight:bold;
    }
    
    #table_id .gt_col_heading {
      color:red;
      font-family:"Source Sans Pro";
      font-weight:bold;
    }
    '
  )
num char fctr date time datetime currency row group
1.111e-01 apricot one 2015-01-15 13:35 2018-01-01 02:22 49.950 row_1 grp_a
2.222e+00 banana two 2015-02-15 14:40 2018-02-02 14:33 17.950 row_2 grp_a
3.333e+01 coconut three 2015-03-15 15:45 2018-03-03 03:44 1.390 row_3 grp_a
4.444e+02 durian four 2015-04-15 16:50 2018-04-04 15:55 65100.000 row_4 grp_a
5.550e+03 NA five 2015-05-15 17:55 2018-05-05 04:00 1325.810 row_5 grp_b
NA fig six 2015-06-15 NA 2018-06-06 16:11 13.255 row_6