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

如何在bslib的card组件内实现Shiny UI元素两列布局?

解决bslib Card内Shiny UI元素并排的两列布局问题

要在bslib的card组件内实现两列并排布局,你可以通过以下两种方法解决,避免不同布局包的样式冲突:

方法1:使用bslib原生layout_columns函数

layout_columns是bslib专为Shiny设计的布局工具,能快速实现响应式列布局:

library(shiny)
library(bslib)

ui <- fluidPage(
  card(
    card_header("Test card"),
    # 用layout_columns设置2列布局
    layout_columns(
      cols = 2,
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30), 
      checkboxInput("Test", "Test checkbox", value = FALSE)
    ),
    plotOutput("distPlot")
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    hist(x, breaks = bins, col = 'darkgray', border = 'white',
         xlab = 'Waiting time to next eruption (in mins)',
         main = 'Histogram of waiting times')
  })
}

shinyApp(ui = ui, server = server)

方法2:使用Bootstrap原生栅格类

直接借助Bootstrap的row和col类手动构建布局,兼容性更强:

library(shiny)
library(bslib)

ui <- fluidPage(
  card(
    card_header("Test card"),
    # 用Bootstrap栅格类实现两列
    div(class = "row",
        div(class = "col",
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)),
        div(class = "col",
            checkboxInput("Test", "Test checkbox", value = FALSE))
    ),
    plotOutput("distPlot")
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    hist(x, breaks = bins, col = 'darkgray', border = 'white',
         xlab = 'Waiting time to next eruption (in mins)',
         main = 'Histogram of waiting times')
  })
}

shinyApp(ui = ui, server = server)

说明

原代码中sliderInput和checkboxInput默认是块级元素,会占满整行宽度导致上下排列。以上两种方法通过将元素放入列容器内,强制它们在同一行显示。

你之前尝试的shinydashboard布局工具无效,是因为bslib的CSS样式与shinydashboard的栅格系统存在冲突,建议优先使用bslib原生工具或Bootstrap原生类实现布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:14:54