如何为Shinydashboard指定盒子设置自定义背景色?
解决方法
因为shinydashboard的box函数background参数只支持预设颜色值,要给单个盒子设置自定义十六进制背景色,有两种简单可行的方式:
方式一:直接添加内联样式
给目标box加上style参数,直接指定背景色,不会影响其他盒子的样式:
修改后的完整代码:
library(shiny) library(shinydashboard) ui <- dashboardPage( dashboardHeader(title = 'Dashboard'), dashboardSidebar(sidebarMenu( menuItem(tabName = 'Panel1', text = 'Panel 1'), dateInput("Start_Date", "Start Date", min = '2000-01-01', max = Sys.Date(), value = '2020-01-01',format = "yyyy-mm-dd") )), dashboardBody( tabItems(tabItem(tabName = 'Panel1', # 替换原background参数,用style指定自定义十六进制颜色(示例为#2c3e50) fluidRow(box(selectizeInput('select_mean', 'Select Number', choices = c(12,24,36,48,60,120)), height=80,width=4, style = "background-color: #2c3e50; color: white;")), # 可选:修改文字颜色提升可读性 fluidRow(box(width = 13, height = 655)) ) ) ) ) server <- function(input, output) {} shinyApp(ui, server)
方式二:自定义CSS(适合多元素复用或复杂样式)
如果需要给多个盒子统一设置样式,或者样式规则更复杂,可以在dashboardBody中添加自定义CSS,先给目标box标记类名,再通过CSS选择器定位:
修改后的完整代码:
library(shiny) library(shinydashboard) ui <- dashboardPage( dashboardHeader(title = 'Dashboard'), dashboardSidebar(sidebarMenu( menuItem(tabName = 'Panel1', text = 'Panel 1'), dateInput("Start_Date", "Start Date", min = '2000-01-01', max = Sys.Date(), value = '2020-01-01',format = "yyyy-mm-dd") )), dashboardBody( # 添加自定义CSS规则 tags$style(HTML(" .custom-bg-box { background-color: #8e44ad !important; /* 自定义十六进制颜色 */ color: white; /* 可选:调整文字颜色 */ } ")), tabItems(tabItem(tabName = 'Panel1', # 给目标盒子添加自定义类名 fluidRow(box(selectizeInput('select_mean', 'Select Number', choices = c(12,24,36,48,60,120)), height=80,width=4, class = "custom-bg-box")), fluidRow(box(width = 13, height = 655)) ) ) ) ) server <- function(input, output) {} shinyApp(ui, server)
两种方式都能单独修改目标盒子的背景色,其余盒子保持默认白色背景。单盒子修改选方式一更直接,多盒子复用样式选方式二更高效。
内容的提问来源于stack exchange,提问作者sa90210
相关产品推荐
相关产品推荐

