如何将shinyWidgets的radioGroupButtons设为5等距列且按钮宽度一致
Got it, let's sort out that radioGroupButtons layout problem! The issue with using column-count is that it treats content like flowing text columns, which doesn't give you consistent button widths or evenly spaced columns. Instead, CSS Grid or Flexbox will give you the precise 5-column layout with equal-width buttons you're after. Here are two reliable solutions:
CSS Grid is made for this kind of layout—it explicitly creates equal-width columns and lets you control spacing with ease. Update your CSS to target a custom class (so you don't mess up other button groups in your app):
.my-radio-grid { display: grid; grid-template-columns: repeat(5, 1fr); /* Creates 5 equal-width columns */ gap: 8px; /* Adjust this value to make spacing tighter/looser */ } .my-radio-grid .btn { width: 100%; /* Makes each button fill its column */ white-space: normal; /* Lets long text wrap instead of truncating */ }
Then apply this class to your radioGroupButtons in the UI:
library(shiny) library(shinyWidgets) my_css <- " .my-radio-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; } .my-radio-grid .btn { width: 100%; white-space: normal; } " ui <- fluidPage( tags$head(tags$style(HTML(my_css))), radioGroupButtons( inputId = "somevalue1", label = NULL, choices = setNames( 1:20, rep(c("xs", "medium", "very long", "a whole lotta text"), 5) ), class = "my-radio-grid" /* Attach our custom grid class */ ) ) server <- function(input, output) {} shinyApp(ui, server)
If you prefer Flexbox, this approach will also work. We'll make the container wrap items and set each button to take up exactly 1/5 of the width (minus spacing):
.my-radio-flex { display: flex; flex-wrap: wrap; gap: 8px; } .my-radio-flex .btn { flex: 1 0 calc(20% - 8px); /* 20% width minus gap size */ white-space: normal; }
Just swap the class in radioGroupButtons to my-radio-flex and you're set.
Quick Tips:
- Using a custom class (instead of targeting all
.btn-group) prevents accidental styling of other button components in your app. white-space: normalensures long button text wraps neatly instead of making buttons unevenly sized.- The
direction = "vertical"approach didn't work because it combines vertical stacking with column-count, which doesn't align items into clean, equal-width columns like Grid or Flexbox do.
内容的提问来源于stack exchange,提问作者yake84

