如何将Shiny应用的外部CSS文件引入flexdashboard
解决flexdashboard中Shiny外部CSS不生效的问题
问题根源
- flexdashboard的YAML配置里
css参数的路径规则和单独Shiny应用不同:它以当前RMD文件为基准查找路径,而非Shiny默认的www资源目录。 - 在flexdashboard中嵌套完整的
shinyApp()会引发样式作用域冲突,flexdashboard的默认样式优先级更高,会覆盖自定义CSS。
解决方案
方案1:使用flexdashboard原生语法(推荐)
flexdashboard本身支持Shiny组件,无需单独初始化shinyApp(),直接编写UI元素即可,同时修正CSS路径:
--- title: 'Dashboard Like a Boss' output: flexdashboard::flex_dashboard: vertical_layout: scroll orientation: rows runtime: shiny css: www/style.css # 指向www目录下的style.css文件 --- ```{r} # 直接添加UI组件,无需嵌套fluidPage和shinyApp tags$p("Hello, world!")
### 方案2:保留shinyApp结构并调整CSS加载方式 如果必须使用完整的`shinyApp()`结构,需要将CSS加载到flexdashboard的全局头部,而非仅在Shiny的UI内部: ```yaml --- title: 'Dashboard Like a Boss' output: flexdashboard::flex_dashboard: vertical_layout: scroll orientation: rows runtime: shiny --- ```{r} # 在flexdashboard全局头部加载CSS,确保作用域覆盖整个页面 tags$head(tags$link(rel = "stylesheet", href = "style.css")) ui <- fluidPage( tags$p("Hello, world!") ) server <- function(input, output, session) { } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Golem
相关产品推荐
相关产品推荐

