如何在R Shinydashboard的box组件中实现文字垂直居中
R Shinydashboard box组件文字垂直居中解决方案
问题原因
- 重复使用同一id不符合HTML规范,同一页面id必须唯一,应该用类选择器批量控制样式
- shinydashboard的
box()渲染后,内容默认包裹在.box-body子元素中,仅给外层box设置flex布局时,内层.box-body未填充满box高度,导致垂直居中不生效
修复方法
1. 替换样式定义
将原id选择器样式替换为类选择器,同时选中box的内容容器.box-body,设置其高度填充满父容器:
tags$style(HTML(' .vertical-center-box .box-body { height: 100%; display: flex; align-items: center; justify-content: center; } '))
2. 给需要垂直居中的box添加类名
给需要居中效果的box()函数添加class = "vertical-center-box"参数即可,无需设置id。
完整可运行修复后代码
# ------------------------------------------------------------------------------ # SET-UP library(shiny) # shiny application library(shinydashboard) # shiny dashboard toolkit rm(list = ls()) # remove variables from working environment shinyOptions(cache = cachem::cache_disk("./app_cache/cache/")) boxHeight = "30em" # Box height # ------------------------------------------------------------------------------ # CREATE DASHBOARD # Header content header <- dashboardHeader( title = span("Play Dashboard", style = "color: white; font-size: 28px"), disable = FALSE, titleWidth = 550 ) # Sidebar content sidebar <- dashboardSidebar( width = 260, collapsed = TRUE, sidebarMenu( menuItem("Dashboard Tab 1", tabName = "tab1", icon = icon("tachometer-alt")) ) ) # Body content body <- dashboardBody( # 修改后的居中样式 tags$style(HTML(' .vertical-center-box .box-body { height: 100%; display: flex; align-items: center; justify-content: center; } ')), tabItems( # 1ST TAB: KEY ECONOMIC INDICATORS tabItem(tabName = "tab1", fluidRow( box(height = boxHeight, class = "vertical-center-box", "This is vertically centered now."), box( height = boxHeight, class = "vertical-center-box", span("This is also vertically centered."), ), box(height = boxHeight, class = "vertical-center-box", span("This works too!")), box(height = boxHeight, "No class added, so no centering effect.") ) ) ) ) server <- function(input,output){ } #Dashboard page dashboard <- dashboardPage(header, sidebar, body, tags$head(tags$style(HTML('* {font-family: "Lucida Sans"}!important;')))) shinyApp(dashboard, server)
内容的提问来源于stack exchange,提问作者Devin Werner
相关产品推荐
相关产品推荐

