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

如何居中RadioButtons并调整Shiny应用显示尺寸

问题解决方案

一、RadioButtons 居中的正确方式

你原代码里的 fluidRow + 零散 column 写法逻辑错误,无法实现居中效果。推荐两种简洁可靠的实现方式:

方式1:内联样式直接居中

给 RadioButtons 包裹一层带居中样式的容器,快速实现对齐:

tags$div(style = "text-align:center;",
  radioButtons('format', 'Document', c('first', 'second', 'third'), inline = TRUE)
)

方式2:利用 Shiny 布局的 align 参数

通过 column 的 align 属性实现布局居中,符合 Shiny 原生逻辑:

fluidRow(
  column(width = 12, 
         radioButtons('format', 'Document', c('first', 'second', 'third'), inline = TRUE),
         align = "center")
)

二、缩小应用窗口至 sidebarPanel 尺寸

通过 CSS 限制应用整体容器宽度,让浏览器窗口可缩小到对应尺寸,同时优化布局空白:

完整修正代码

library(shiny)

ui <- fluidPage(
  title = 'report',
  # 自定义CSS限制应用宽度,优化窗口尺寸
  tags$head(
    tags$style(HTML("
      .container-fluid {
        width: 360px; /* 按需调整宽度 */
        margin: 0 auto;
      }
      .radio-inline {
        margin: 0 10px; /* 调整按钮间的间距 */
      }
    "))
  ),
  # 让侧边栏占满容器宽度,消除多余空白
  sidebarPanel(
    width = 12,
    # 居中显示RadioButtons
    tags$div(style = "text-align:center;",
      radioButtons('format', 'Document', c('first', 'second', 'third'), inline = TRUE)
    ),
    # 下载按钮也居中对齐
    tags$div(style = "text-align:center; margin-top:15px;",
      downloadButton('downloadReport')
    )
  )
)

server <- function(input, output, session) {
  session$onSessionEnded(function() {
    stopApp()
  })
}

shinyApp(ui, server)

额外优化:启动时自动调整窗口大小

如果希望应用打开时直接适配尺寸,可借助 shinyjs 调用 JS 调整窗口(需先安装 shinyjs 包):

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  title = 'report',
  # 同上的CSS和布局代码
  # ...
)

server <- function(input, output, session) {
  session$onSessionEnded(function() {
    stopApp()
  })
  # 启动时设置窗口大小
  runjs("window.resizeTo(390, 260);")
}

shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者Salvador

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:52:36