rgt

Adding a border to the column label row in gt


Is it possible to add borders to the column label row of a gt table? For example:

# Create a simple 4x4 data frame
data <- data.frame(
  Column_1 = c("A", "B", "C", "D"),
  Column_2 = c(1, 2, 3, 4),
  Column_3 = c(5.5, 6.5, 7.5, 8.5),
  Column_4 = c(TRUE, FALSE, TRUE, FALSE)
)

# Generate a `gt` table
gt_table <- data %>%
  gt() %>%
  tab_header(
    title = "Simple 4x4 Table",
    subtitle = "For Testing Column Labels"
  ) %>%
  tab_style(
    style = cell_borders(sides = "bottom", weight = px(1)),
    locations = list(
      cells_column_labels(),
      cells_body(rows = 1)
    )
  )

# Display the table
gt_table

The bottom border for the row containing "A" appears, but the bottom border for the column labels (i.e Column_1, Column_2 etc) does not. Image of generated table


Solution

  • This is due to a CSS rule conflict where the default border style applied to the top table body and the bottom column labels (a border width of 2px) takes precedence over the new 1px rule. It can be resolved by setting the existing style rules for this border to none (or the width to <= 1px).

    library(gt)
    
    # Generate a `gt` table
    data %>%
      gt() %>%
      tab_header(
        title = "Simple 4x4 Table",
        subtitle = "For Testing Column Labels"
      ) %>%
      tab_style(
        style = cell_borders(sides = "bottom", weight = px(1)),
        locations = list(
          cells_column_labels(),
          cells_body(rows = 1)
        )
      ) %>%
      tab_options(column_labels.border.bottom.style = "none",
                  table_body.border.top.style = "none")  
    

    enter image description here

    More info on border conflicts can be found here