在R和/或LeafletR的htmlwidgets中是否可以包含自定义CSS?

10

我想对我的leaflet地图进行一些样式更改。

是否可以通过htmlwidgets for R或LeafletR来包含以下内容:

  • 样式元素或
  • 自定义路径到css文件

请提供相关翻译。

谢谢。


你有一点可重现的代码或自定义leaflet样式的例子吗?我想我有一个答案,但我不确定。htmltools在这里肯定会帮到你,但我们还可以使用依赖项来探索其他选项。 - timelyportfolio
你是否在使用rmarkdown - timelyportfolio
不,我不使用rmarkdown。我想在一个独立的网站上使用它。 - kabr
2个回答

15

没有在您的问题中提供任何代码,回答是非常困难的。我会尝试回答。有两种方法可以将自定义CSS添加到htmlwidget中。我要提前告诫一下,您需要非常具体或使用!important覆盖,因为已经有相当一部分CSS被自动添加到leaflet中了。此处

简单但不够健壮

htmlwidgets可以与htmltools包中的tags结合使用。

library(leaflet)
library(htmltools)

# example from ?leaflet
m = leaflet() %>% addTiles()

# there are two approaches to the custom css problem
#  1.  the easy but less robust way
browsable(
  tagList(list(
    tags$head(
      # you'll need to be very specific
      tags$style("p{font-size:200%;}")
      # could also use url
      #tags$link(href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css",rel="stylesheet")
    ),
    m
  ))
)

使用htmlDependency更加强大

您还可以使用htmlDependency来处理重复导致的冲突。

#  2.  you can add dependencies to your leaflet map
#  this mechanism will smartly handle duplicates
#  but carries a little more overhead
str(m$dependencies)  # should be null to start
# 
m$dependencies <- list(
  htmlDependency(
    name = "font-awesome"
    ,version = "4.3.0"
    # if local file use file instead of href below
    #  with an absolute path
    ,src = c(href="http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css")
    ,stylesheet = "font-awesome.min.css"
  )
)

m

谢谢。正是我所需要的。 - kabr

0
我按照timelyportfolio的可浏览方法进行了操作,但是地图只显示在一个小窗口中。要解决这个问题,你需要给leaflet添加100vw和100vh,并且去掉body的边距。
例如:
library(leaflet)
library(htmltools)

# example from ?leaflet
m = leaflet(height = '100vh', width = '100vw') %>% addTiles()

# there are two approaches to the custom css problem
#  1.  the easy but less robust way
browsable(
  tagList(list(
    tags$head(
      # you'll need to be very specific
      tags$style("p{font-size:200%;} body{margin: 0px;}")
      # could also use url
      #tags$link(href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css",rel="stylesheet")
    ),
    m
  ))
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接