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

Shiny dashboard中valueBox颜色不生效且文本不居中问题咨询

问题根因

shinydashboard的valueBox功能默认依赖dashboardPage布局的专属样式,你当前使用fluidPage + sidebarLayout的结构没有加载对应的样式表,因此颜色参数不生效、排版也不符合预期。


方案1:修复现有valueBox的样式

直接在UI中补充自定义CSS即可实现navy底色、白色居中文字的效果,无需修改原有逻辑:

library(shinydashboard)
library(shiny)
library(dplyr)
library(tibble)

ui <- fluidPage(
  # 新增自定义CSS适配valueBox样式
  tags$style("
    .small-box {
      background-color: #001f3f !important; /* navy色对应的十六进制码 */
      color: white !important;
      text-align: center !important;
    }
    .small-box h3, .small-box p {
      color: white !important;
    }
  "),
  sidebarLayout(
    sidebarPanel(
      textInput(inputId = "greeting",
                label = "Say hi!"),
      actionButton(inputId = "submit", 
                   label = "Submit")
      
    ),
    mainPanel(
      valueBoxOutput("total_projects")
    )
  ))
server <- function(input, output) {
  
  data <- tibble(name = c("Justin", "Corey", "Sibley"),
                 grade = c(50, 100, 100))
  
  
  output$total_projects <- renderValueBox({
    shiny::req(input$greeting)
    shiny::req(input$submit)
    if(input$greeting == "hi!") {
      num_100s <- data %>% filter(grade == 100) %>% nrow()
      valueBox(value = num_100s, subtitle = "Number of Perfect Scores",
               width = 3)
    }
  })
}
shinyApp(ui, server)

方案2:使用更灵活的bslib::value_box(推荐)

bslib是官方维护的Bootstrap适配包,其中的value_box功能不依赖特定布局,支持任意自定义颜色、图标、排版配置,灵活度远高于shinydashboard的valueBox:

library(shiny)
library(dplyr)
library(tibble)
library(bslib)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput(inputId = "greeting",
                label = "Say hi!"),
      actionButton(inputId = "submit", 
                   label = "Submit")
      
    ),
    mainPanel(
      # bslib的valueBox输出组件
      value_box_output("total_projects")
    )
  ))
server <- function(input, output) {
  
  data <- tibble(name = c("Justin", "Corey", "Sibley"),
                 grade = c(50, 100, 100))
  
  
  output$total_projects <- render_value_box({
    shiny::req(input$greeting)
    shiny::req(input$submit)
    if(input$greeting == "hi!") {
      num_100s <- data %>% filter(grade == 100) %>% nrow()
      value_box(
        title = "Number of Perfect Scores",
        value = num_100s,
        # 支持任意颜色配置,直接传颜色名、十六进制码都可以
        bg = "navy",
        text_color = "white",
        height = "150px",
        alignment = "center"
      )
    }
  })
}
shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者J.Sabree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 20:36:08