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

如何用HTML/CSS实现Shiny中所有组件的同行对齐?

解决Shiny组件同行对齐问题

你的代码功能正常,但需要调整UI布局,让按钮、初始表格以及新增的表格都在同一行对齐。只需修改ui部分,将初始的按钮和表格组件按行内块样式布局,同时确保所有元素垂直对齐方式一致即可。

修改后的完整代码如下:

library(rhandsontable)
library(shiny)

rowNames1 <- c("A", "B", "C", "Sum")
data1 <- data.frame(row.names = rowNames1, "Col 1" = c(1, 1, 0, 2), check.names = FALSE)

ui <- fluidPage(
  tags$div(
    style = "display: inline-block; margin-right: 10px; vertical-align: top;",
    actionButton("addTbl", "Add table")
  ),
  tags$div(
    style = "display: inline-block; margin-right: 10px; vertical-align: top;",
    rHandsontableOutput("hottable1")
  ),
  tags$div(id = "placeholder")            
)

server <- function(input, output) {
  uiTbl1 <- reactiveValues(base = data1)  

  observeEvent(input$hottable1,{uiTbl1$base <- hot_to_r(input$hottable1)})
  
  output$hottable1 <- renderRHandsontable({
    rhandsontable(uiTbl1$base, rowHeaderWidth = 100, useTypes = TRUE)
  })
  
  observeEvent(input$addTbl, {
    divID <- gsub("\\.", "", format(Sys.time(), "%H%M%OS3"))
    dtID <- paste0(divID, "DT")
    uiTbl1[[paste0(divID,"tbl")]] <- data1 
    
    insertUI(
      selector = "#placeholder",
      ui = tags$div(
        id = divID,
        style = "display:inline-block; margin-right: 10px; margin-top: 10px; vertical-align: top;",
        rHandsontableOutput(dtID),
        hr()
      )
    )
    output[[dtID]] <- renderRHandsontable({
      req(uiTbl1[[paste0(divID,"tbl")]])
      rhandsontable(uiTbl1[[paste0(divID,"tbl")]], rowHeaderWidth = 100, useTypes = TRUE)
    })
  })
}

shinyApp(ui, server)

关键修改说明:

  • 给初始的按钮和表格分别添加display: inline-block样式,让它们从默认的块级元素变为行内块元素,可在同一行排列
  • 统一设置vertical-align: top,确保所有组件顶部对齐,避免因元素高度不同出现错位
  • 保留了原有代码的自动换行逻辑,当页面宽度不足时,元素会自动换行到下一行

内容的提问来源于stack exchange,提问作者Village.Idyot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:25:25