Home > database >  How to use INLINE HTML to make text white on dark background automatically after setting background
How to use INLINE HTML to make text white on dark background automatically after setting background

Time:01-16

This question is somehow related but not depending to this enter image description here

I would like to have the text in mpg column in white color conditional to dark background coded in the inline html part of my code e.g. before transforming to an gt object.

While this works: This is not what I am looking for!

library(dplyr)
library(gt)
library(viridis)

head(mtcars[,1:2]) %>%  
  gt() %>% 
  data_color(
    columns = c(mpg),
    colors = scales::col_numeric(
      palette = viridis(20, direction = 1, option ="D"), #color from viridis package
      domain = NULL)
  )

gives:

enter image description here

I have tried so far: adding color:white to inline html

head(mtcars[,1:2]) %>% 
  mutate(
    color = scales::col_numeric(
      palette = viridis(20, direction = 1, option ="D"), #color from viridis package
      domain = NULL)(mpg),
    mpg = glue::glue('<span style=\"display: inline-block; direction: ltr; color:white; border-radius: 5px; padding-right: 2px; background-color: {color}; width: 100%\"> {mpg} </span>'),
    mpg = map(mpg, ~gt::html(as.character(.x)))
  ) %>% 
  select(-color) %>% 
  gt()

which gives:

enter image description here

CodePudding user response:

One option would be prismatic::best_contrast. By default it will not use pure white so we have to set the colors:

prismatic::best_contrast("red", c("white", "black"))
#> [1] "black"

prismatic::best_contrast("purple", c("white", "black"))
#> [1] "white"

This could be added easily to your glue string to set font color based on the background color:

head(mtcars[, 1:2]) %>%
  mutate(
    color = scales::col_numeric(
      palette = viridis(20, direction = 1, option = "D"), # color from viridis package
      domain = NULL
    )(mpg),
    mpg = glue::glue(
      '<span style=\"display: inline-block; direction: ltr; border-radius: 5px; padding-right: 2px;',
      'color: {prismatic::best_contrast(color, c("white", "black"))}; background-color: {color}; width: 100%\"> {mpg} </span>'
    ),
    mpg = map(mpg, ~ gt::html(as.character(.x)))
  ) %>%
  select(-color) %>%
  gt()

enter image description here

  •  Tags:  
  • Related