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

如何在Shiny中实现两组单选按钮的目标对齐效果?

解决Shiny中两组单选按钮的对齐问题

原问题情况

当前运行效果:
当前效果

期望实现的效果:
期望效果

可以通过调整CSS,给每个单选选项设置固定宽度并让文本右对齐,来实现单选按钮的垂直对齐。修改后的代码如下:

library(shiny)

ui <- fluidPage(tags$style(HTML(
    "
    .radio-inline {
      display: inline-block;
      width: 120px; /* 根据文本长度调整宽度 */
      text-align: right;
      margin-right: 20px;
    }
    .radio-inline input {
      margin-left: 8px;
    }
    "
    )),
    radioButtons(
      "MPL1", label="Label 1", 
      choiceNames=c("yes","no"), 
      choiceValues=c(0,1), 
      selected= character(0),
      inline=TRUE
    ),
    radioButtons(
      "MPL2", label="Label 2", 
      choiceNames=c("(lorem yes)","(ipsum yes)"), 
      choiceValues=c(0,1), 
      selected= character(0),
      inline=TRUE
    )
    )

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

shinyApp(ui, server)

原理说明

  • 将.radio-inline设置为固定宽度的内联块元素,保证每组选项的容器尺寸统一
  • 文本右对齐,让单选按钮固定在文本左侧,不同组的单选按钮自然会垂直对齐
  • 可根据选项文本的实际长度调整width参数,确保显示完整且对齐准确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:20:11