Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom styling with prependContent #231

Open
timelyportfolio opened this issue Sep 7, 2016 · 1 comment
Open

custom styling with prependContent #231

timelyportfolio opened this issue Sep 7, 2016 · 1 comment

Comments

@timelyportfolio
Copy link
Collaborator

timelyportfolio commented Sep 7, 2016

I'm not sure there is a broad enough use case for custom CSS styling to add to this package, but I thought I would mention this in case someone is interested. I know I have seen a couple of htmlwidgets that used JavaScript to inject page-wide custom CSS. I think using an id selector with CSS specificity might be a better solution. Here is some quick code and post to illustrate the concept.

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

# 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
      )
    )
  )
}

# 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")
  )
)

htmlwidget_custom_style

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants