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

如何用CSS实现Shiny Widgets数值输入框与标签的垂直居中对齐?

解决Shiny中autonumericInput与标签垂直居中对齐问题

问题根源

shinyWidgets::autonumericInput生成的DOM元素默认带有垂直外边距,且内部组件布局会导致整体偏移,即使容器设置了align-items: center也无法完全对齐。

修复方案

通过以下调整实现自适应垂直居中:

  • 给autonumericInput包裹flex容器,清除默认外边距并确保内部垂直居中
  • 给标签添加适当间距优化布局美观度

修改后的完整代码

library(shiny)
library(shinyWidgets)

numInputFun <- function(
    inputId,
    value = 60,
    ns = identity
) {
  label <- tags$span(
    style = "display: flex; align-items: center; margin-right: 10px;",
    "Periods (x-axis):"
  )
  container_style <- paste0(
    "background-color: #f0f0f0;",
    "display: flex;",
    "align-items: center;",
    "height: 34px;",
    "padding: 0 8px;" # 可选:添加左右内边距避免内容贴边
  )
  input_box <- div(
    style = "display: flex; align-items: center; margin: 0;",
    autonumericInput(
      inputId = ns(inputId),
      label = NULL,
      value = value,
      style = paste0("height: 28px;")
    )
  )
  div(
    style = container_style,
    label,
    input_box
  )
}

mod30_A_ui <- function(id) {
  ns <- NS(id)
  tagList(
    br(),
    numInputFun(inputId = "periods", ns = ns)
  )
}

mod30_A_server <- function(id, mod10_data = NULL) {
  moduleServer(id, function(input, output, session) {
    # 可在此添加服务器逻辑
  })
}

# 测试用主应用
ui <- fluidPage(mod30_A_ui("mod30_A"))
server <- function(input, output, session) { 
  mod30_A_server("mod30_A") 
}
shinyApp(ui, server)

关键调整说明

  1. 输入框外层容器:用div包裹autonumericInput,设置margin: 0抵消默认垂直外边距,display: flex; align-items: center确保输入框内部元素垂直居中。
  2. 标签间距:给标签添加margin-right: 10px,让标签与输入框保持合理间距。
  3. 容器内边距(可选):给外层容器添加padding: 0 8px,避免内容紧贴容器边缘,提升视觉效果。

修改后,无论容器高度如何调整(比如将height:34px改为height:50px),标签和输入框都会自动保持垂直居中对齐。

内容的提问来源于stack exchange,提问作者Village.Idyot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:59:52