Custom Styling for htmlwidgets

In this DT Github issue, there was a need to apply custom styling for htmlwidgets. I wrote a quick helper function to apply my solution based on CSS specificity rules. We use htmlwidgets::prependContent to add a style tag using a CSS id selector. Using this method means we don't have to use JavaScript to inject our custom CSS.

helper function

# define function to help apply custom css
#  to htmlwidgets using css specificity with id
style_widget <- function(hw=NULL, style="", addl_selector="") {
  stopifnot(!is.null(hw), inherits(hw, "htmlwidget"))

  # use current id of htmlwidget if already specified
  elementId <- hw$elementId
  if(is.null(elementId)) {
    # borrow htmlwidgets unique id creator
    elementId <- sprintf(
      'htmlwidget-%s',
      htmlwidgets:::createWidgetId()
    )
    hw$elementId <- elementId
  }

  htmlwidgets::prependContent(
    hw,
    htmltools::tags$style(
      sprintf(
        "#%s %s {%s}",
        elementId,
        addl_selector,
        style
      )
    )
  )
}

example

Here is a quick example with rpivotTable.

library(htmltools)
library(htmlwidgets)
library(rpivotTable)

# use rpivotTable to illustrate the effect
rp <- rpivotTable(UCBAdmissions, height=200)

browsable(
  tagList(
    rp,
    style_widget(hw=rp, "font-family:monospace;"),
    style_widget(hw=rp, "font-size:150%; color:purple;", "table td")
  )
)

...and a screenshot of the result.

htmlwidget_custom_style.png