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

R Shiny中如何实现单选按钮文本与图标左对齐且同行显示?

解决R Shiny单选按钮文本与图标左对齐问题

问题原因

原代码仅调整了文本所在<p>标签的对齐方式,但radioGroupButtons生成的按钮内部,图标和文本属于独立布局元素,默认图标存在固定位置或内边距设置,因此单独修改文本对齐无法同步带动图标位置。

解决方案

通过调整按钮容器、图标及文本的CSS布局规则,实现两者左对齐且同行显示:

library(shinyWidgets)

ui <- fluidPage(
  tags$style(
    # 统一按钮内部元素左对齐布局
    ".btn-group-vertical > .btn {
      justify-content: flex-start;
      text-align: left;
    }
    #Id067 .check-icon {
      margin-right: 8px; /* 图标与文本间保留间距 */
    }
    .first-p {
      margin: 0; /* 移除p标签默认外边距,避免文本换行 */
    }"
  ),

  radioGroupButtons(
    inputId = "Id067",
    label = "Label",
    choiceNames = list( 
      p(class = "first-p", "Yes (Start the survey)"),
      p(class = "first-p", "No (End the survey)")
    ),
    choiceValues = list("yes", "no"),
    direction = "vertical",
    selected = character(0),
    width   = "100%",
    status = 'success',
    size = 'normal',
    checkIcon = list(
      yes = icon("ok", lib = "glyphicon")
    )
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

关键CSS说明

  • .btn-group-vertical > .btn:针对垂直布局的按钮容器,设置justify-content: flex-start让内部图标与文本整体左对齐,text-align: left确保文本自身左对齐。
  • #Id067 .check-icon:定位目标按钮组的图标元素,设置右边距避免图标与文本紧贴。
  • .first-p:移除p标签默认的上下外边距,防止文本因间距过大换行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:30:43