You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除rmarkdown::run生成的带shiny runtime的html_document中的Bootstrap CSS

彻底移除Shiny Rmd中的Bootstrap CSS

当使用runtime: shiny的Rmarkdown文档时,仅设置theme: null无法彻底移除Bootstrap——因为Shiny本身会自动注入其核心UI依赖的Bootstrap资源,这部分不受html_document的theme配置控制。以下是可行的解决方案:

核心思路

绕过Shiny的默认页面组件(如fluidPage、basicPage),手动构建完整的HTML结构,让Shiny无法自动加载Bootstrap,同时保留交互功能。

修改后的完整Rmd代码

---
title: "xxx"
output:
  html_document:
    theme: null  # 禁止rmarkdown加载Bootstrap
runtime: shiny
---

```{r echo=FALSE, message=FALSE, warning=FALSE}
# 手动构建HTML页面结构,完全自定义资源加载
shiny::tags$html(
  shiny::tags$head(
    # 加载你的自定义CSS(这里用Bulma示例,可替换为本地路径)
    shiny::tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.4/css/bulma.min.css"),
    # 可选:添加内联自定义样式
    shiny::tags$style("body { padding: 2rem; }")
  ),
  shiny::tags$body(
    # 页面内容+Shiny交互组件
    shiny::tags$div(class = "container",
      shiny::tags$h1(class = "title", "无Bootstrap的Shiny页面"),
      shiny::tags$div(class = "field",
        shiny::tags$label(class = "label", "输入姓名"),
        shiny::textInput("name", "", placeholder = "请输入你的名字")
      ),
      shiny::tags$p(class = "subtitle", shiny::textOutput("greeting"))
    )
  )
)

# Shiny服务器逻辑
shiny::function(input, output) {
  output$greeting <- shiny::renderText({
    if(nchar(input$name) > 0) paste("你好,", input$name, "!") else "请输入你的名字"
  })
}
## 关键说明
1. **禁用双端Bootstrap加载**:YAML中的`theme: null`阻止rmarkdown的`html_document`模块加载Bootstrap;手动构建HTML结构则阻止Shiny自动注入其自带的Bootstrap资源。
2. **自定义资源引入**:在`tags$head`中直接引入你的CSS文件(远程或本地路径均可),完全控制页面样式。
3. **保留交互功能**:依然可以正常使用Shiny的输入输出组件,只需将它们放在手动构建的`tags$body`中即可。

如果需要使用本地CSS文件,可通过`shiny::addResourcePath`映射路径,示例:
```r
# 在代码块开头添加
shiny::addResourcePath("css", "./css")
# 然后在tags$head中引入
shiny::tags$link(rel = "stylesheet", href = "css/custom.css")

内容的提问来源于stack exchange,提问作者stallingOne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:53:13