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

如何在bslib::value_box()组件中实现值的水平对齐?

解决bslib数值框(value_box)值对齐问题

问题根源在于不同长度的标题会占用不同垂直空间,导致数值区域位置偏移。以下是两种直接有效的解决方法:


方法一:让数值区域强制对齐到底部

通过自定义CSS,让每个数值框的内容容器采用弹性布局,将数值区域推到底部,无论标题长度如何,数值都会保持同一水平线:

.bi-value-box .value-box-body {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.bi-value-box .value-box-value {
  margin-top: auto;
}

方法二:固定标题区域高度

给所有数值框的标题设置统一最小高度,确保标题区域占用相同垂直空间,数值自然对齐:

.bi-value-box .value-box-title {
  min-height: 4rem; /* 根据最长标题高度调整数值 */
  display: flex;
  align-items: center;
}

修改后的完整示例(内嵌CSS版本)

直接将CSS内嵌到Quarto文档中,无需额外文件:

---
title: "Value Box Alignment Example"
format:
  dashboard:
    expandable: false
server: shiny
---

```{css, echo=FALSE}
/* 采用方法一的对齐逻辑 */
.bi-value-box .value-box-body {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.bi-value-box .value-box-value {
  margin-top: auto;
}
#| label: load-packages
#| context: setup
#| message: false

library(shiny)
library(bslib)

Main body

Value boxes {height="20%"}

value_box(
title = "Cases",
value = textOutput("cases_val"),
theme = "teal"
)
value_box(
title = "Some very long text dajsndasndonasddsadasd",
value = textOutput("deaths_val"),
theme = "teal"
)
value_box(
title = "Recovered",
value = textOutput("recovered_val"),
theme = "teal"
)
value_box(
title = "Vaccinated",
value = textOutput("vax_val"),
theme = "teal"
)
value_box(
title = "Tests",
value = textOutput("tests_val"),
theme = "teal"
)

Row {height="80%"}

#| context: server

output$cases_val <- renderText({ "123" })
output$deaths_val <- renderText({ "4" })
output$recovered_val <- renderText({ "12,345" })
output$vax_val <- renderText({ "85%" })
output$tests_val <- renderText({ "999,999" })
### 补充说明
- 方法一无需手动计算标题高度,适配性更强;方法二适合标题长度差异不大的场景。
- 可根据需求调整CSS中的`min-height`或间距参数,优化视觉效果。

内容的提问来源于stack exchange,提问作者magus
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:37:41