如何固定Shiny应用底部元素避免随内容下移?
解决Shiny应用左侧元素固定底部的问题
要让左侧栏的Counts区域固定在页面底部,不受上方选中动物数量变化的影响,你可以用CSS弹性布局(flexbox)改造左侧列的结构,具体修改如下:
修改后的完整代码
library(tidyverse) library(ggplot2) library(dplyr) library(shiny) # Define UI for app ui <- fillPage( column(2, # 外层容器设置弹性布局,垂直排列 div(style = "height: 100%; display: flex; flex-direction: column;", fluidRow( # Input 1: animal selectInput( inputId = 'FilterFieldSelection', label = 'Animal Of Choice', choices = c('Dog','Cat','Inu','Neko','Giraffe','Kirin','Mouse','Nezumi'), selected = 'Dog', multiple = TRUE ), # Output 1: Active Filters htmlOutput('ActiveFiltersText') ), # 下方区域设置margin-top:auto,自动对齐底部 div(style = "margin-top: auto;", fluidRow( h4("Counts"), # Input 2: color selectInput( inputId = 'ColorChoice', label = 'Color Of Choice', choices = c('red','blue','green'), selected = 'red' ), # Output 2: Filtered Well Count htmlOutput('WellCountFilteredText'), ) ) ) ), column(10, plotOutput('myplot') ) ) # Define Server server <- function(input, output, session) { # Text Outputs ---- ## Text Output Of Active Filters ---- output$ActiveFiltersText <- renderUI({ full_text <- "" full_text <- paste0(full_text, '<b>','There Is A','</b>:<br/>', paste(input$FilterFieldSelection,collapse="<br/>"),'<br/>' ) full_text <- HTML(full_text) }) ## Text Output Of Filtered Well Count ---- output$WellCountFilteredText <- renderUI({ HTML(paste0('<b>','Filtered','</b>:<br/>',150000)) }) ## Plot output$myplot <- renderPlot({ m <- matrix(rnorm(50), ncol = 5) colnames(m) <- c("a", "b", "c", "d", "e") as_tibble(m) %>% ggplot(aes(x=a, y=b) ) + geom_point(color=input$ColorChoice) }) } # Run App shinyApp(ui = ui, server = server)
关键修改说明
- 给左侧
column(2)内部添加外层div,设置height: 100%; display: flex; flex-direction: column;,让容器占满左侧栏全部高度,内部元素垂直排列。 - 将需要固定在底部的Counts区域放入单独
div,设置margin-top: auto;,这个属性会自动把该区域推到容器底部,不受上方内容高度变化影响。
修改后,无论选中多少动物导致上方内容变长,下方的Counts区域都会始终固定在左侧栏底部,不会被顶下移。
内容的提问来源于stack exchange,提问作者Spruce
相关产品推荐
相关产品推荐

