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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:15:03