Little Inline Color Boxes

R Markdown Source

Color Boxes with R

color_preview <- function(color) {
  htmltools::tagList(
    htmltools::span(
      class = "color-preview",
      style = paste("background-color:", color),
      .noWS = "outside"
    ),
    htmltools::code(color, .noWS = "outside"),
    color_preview_dep()
  )
}

CSS Dependency

You’ll need to copy this function too, and feel free to tweak it if you want. For example, remove the border-radius line to get squares instead of circles. Or remove the .color-preview:hover rule to have static previews.

color_preview_dep <- function() {
  htmltools::htmlDependency(
    name = "color_preview",
    version = "0.0.1",
    src = ".",
    all_files = FALSE,
    head = "
<style>.color-preview {
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 50%;
  margin: 0 0.33em;
  vertical-align: middle;
  transition: transform 100ms ease-in-out;
}

.color-preview:hover {
  cursor: pointer;
  transform: scale(2);
  transform-origin: 50% 50%;
}</style>"
  )
}

One of my favorite color resources coolors.co. It gives you a palette of random colors, like #414073 or #70a37F. Press the space bar to get new colors, or you can lock in colors you like to find new ones that work with colors you’ve already picked out.

Here’s another color coolors picked for me:

color_preview("rgb(114, 9, 183)")

rgb(114, 9, 183)

You can even find color palettes, like this one.

R code…

# https://coolors.co/ef476f-ffd166-06d6a0-118ab2-073b4c
colors <- c(
  "#ef476f",
  "#ffd166",
  "#06d6a0",
  "#118ab2",
  "#073b4c"
)

items <- lapply(colors, function(color) {
  htmltools::tags$li(color_preview(color))
})
htmltools::tags$ul(items)
  • #ef476f
  • #ffd166
  • #06d6a0
  • #118ab2
  • #073b4c