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

如何在ShinyDashboard中通过自定义CSS修改infoBox颜色?

自定义ShinyDashboard中infoBox的颜色(CSS实现)

操作步骤:

  1. 给目标infoBox添加自定义类
    在server端的infoBox函数里新增class参数,指定一个自定义类名(比如custom-info-box),方便CSS精准定位:

    # 修改后的第一个infoBox
    infoBox("Responses submitted", ParterCount$count, icon=icon("pencil-square-o"), 
            color = "red", fill = F, class = "custom-info-box")
    
    # 修改后的第二个infoBox
    infoBox("Contact Person", unique(Contact), icon=icon("user"), 
            color = "red", fill = F, class = "custom-info-box")
    
  2. 添加自定义CSS样式
    在UI端的dashboardBody内,通过tags$head插入CSS代码,覆盖默认的红色样式。你可以根据需求调整颜色(示例用薄荷绿#2ecc71):

    dashboardBody(
      tags$head(
        tags$style(HTML("
          /* 自定义infoBox图标颜色 */
          .custom-info-box .info-box-icon {
            color: #2ecc71;
          }
          /* 自定义infoBox左侧边框颜色(fill=F时的标志性色条) */
          .custom-info-box {
            border-left: 4px solid #2ecc71;
          }
          /* 可选:修改标题文字颜色 */
          .custom-info-box .info-box-text {
            color: #2ecc71;
          }
          /* 可选:修改数值文字颜色 */
          .custom-info-box .info-box-number {
            color: #2ecc71;
          }
        "))
      ),
      # 放置infoBox的输出容器
      infoBoxOutput("responseBox"),
      infoBoxOutput("contactBox")
    )
    

完整示例代码:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Custom InfoBox Demo"),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$style(HTML("
        .custom-info-box .info-box-icon {
          color: #2ecc71;
        }
        .custom-info-box {
          border-left: 4px solid #2ecc71;
        }
        .custom-info-box .info-box-text {
          color: #2ecc71;
        }
        .custom-info-box .info-box-number {
          color: #2ecc71;
        }
      "))
    ),
    infoBoxOutput("responseBox"),
    infoBoxOutput("contactBox")
  )
)

server <- function(input, output) {
  # 模拟数据(替换成你的实际数据)
  ParterCount <- data.frame(count = 123)
  Contact <- "John Doe"
  
  output$responseBox <- renderInfoBox({
    infoBox("Responses submitted", ParterCount$count, icon=icon("pencil-square-o"), 
            color = "red", fill = F, class = "custom-info-box")
  })
  
  output$contactBox <- renderInfoBox({
    infoBox("Contact Person", unique(Contact), icon=icon("user"), 
            color = "red", fill = F, class = "custom-info-box")
  })
}

shinyApp(ui, server)

说明:

  • 把代码中的#2ecc71替换成你需要的十六进制颜色码、RGB值或颜色名称(比如purple)即可。
  • 如果不需要修改标题或数值颜色,可以删除对应的CSS规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:31:21