如何调整Shiny中两个居中等宽操作按钮的间距?
解决Shiny中等宽按钮居中且间距可控的问题
我来帮你搞定这个按钮间距的难题~ 先拆解下你之前遇到的问题:
- 最初把两个按钮放在同一列时,按钮默认排版导致间距过小,而且你之前写错了CSS属性(应该是
margin-left而不是margin.left,CSS属性名是横杠分隔的),所以修改没生效。 - 分成两列后间距太大,是因为Shiny的
column默认带有左右内边距(padding),加上两列的宽度分配,导致按钮之间的空白过多。
下面给你几个实用的解决方案:
方案1:同一列内用CSS直接控制间距(最简单)
直接在同一列里给按钮设置margin属性控制间距,同时保持按钮居中:
library(shiny) ui <- fluidPage( fluidRow( align = "center", br(), column( 12, actionButton( inputId = "ab1", label = "Left button", style = "width:400px; margin-right: 50px;" # 右侧留50px间距 ), actionButton( inputId = "ab2", label = "Right button", style = "width:400px;" ) ) ) ) server <- function(input, output) {} shinyApp(ui, server)
你可以调整margin-right的数值来控制两个按钮之间的距离,比如改成30px就是更小的间距。
方案2:调整column的宽度与内边距(保留分栏逻辑)
如果想继续用分栏的方式,可以缩小column的宽度,同时调整列的内边距来减少多余空白:
library(shiny) ui <- fluidPage( fluidRow( align = "center", br(), column( 5, # 把默认6改成5,压缩列宽 actionButton( inputId = "ab1", label = "Left button", style = "width:400px;" ), style = "padding-right: 10px;" # 调整列的右内边距 ), column( 5, # 同样改成5 actionButton( inputId = "ab2", label = "Right button", style = "width:400px;" ), style = "padding-left: 10px;" # 调整列的左内边距 ) # 剩下的2列留空,保证整体居中 ) ) server <- function(input, output) {} shinyApp(ui, server)
通过调整列宽和内边距的数值,可以精准控制按钮之间的间距大小。
方案3:用Flex布局(最灵活现代)
用CSS Flex布局来控制按钮排列,这种方式更直观,调整间距、对齐方式都很方便:
library(shiny) ui <- fluidPage( fluidRow( style = "display: flex; justify-content: center; gap: 30px; padding-top: 15px;", # justify-content: center 让按钮居中,gap直接控制间距 actionButton( inputId = "ab1", label = "Left button", style = "width:400px;" ), actionButton( inputId = "ab2", label = "Right button", style = "width:400px;" ) ) ) server <- function(input, output) {} shinyApp(ui, server)
这里gap: 30px就是两个按钮之间的间距,直接修改数值就能调整,非常灵活。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

