如何阻止bslib的card_title组件自动调整尺寸?
解决方案:bslib复刻shinydashboardPlus右侧边栏与固定card_title
一、固定card_title高度
card_title默认会在fill容器中自动拉伸填充剩余空间,这是因为它作为card的flex子项默认flex-grow:1。要让它和card_header、card_footer一样保持固定尺寸,只需给card_title添加Bootstrap内置的flex-grow-0类,无需额外自定义CSS:
card_title(class = "flex-grow-0", "this is the title, i don't want it to resize with sidebar collapse or to be sized too tall")
二、右侧边栏覆盖主体内容
要实现右侧边栏打开时覆盖而非挤压主体内容,只需在右侧sidebar的参数中设置overlay = TRUE,这是bslib内置的功能,无需额外样式:
sidebar( width = 800, position = "right", open = "closed", overlay = TRUE, # 开启覆盖模式 p("right sidebar contents...") )
修改后的完整代码
library(shiny) library(bslib) ui <- page_fillable( title = "Page Fillable Template", theme = bs_theme(bootswatch = "pulse"), fillable_mobile = TRUE, #narrow windows card( # 给card_title添加flex-grow-0类固定高度 card_title(class = "flex-grow-0", "this is the title, i don't want it to resize with sidebar collapse or to be sized too tall" ), card_header( "This is the header, its size stays fixed... me likey" ), card_body( padding = c(0, 0, 0, 0), #让左侧侧边栏与容器对齐 #左侧侧边栏组件 layout_sidebar( padding = c(0, 0, 0, 0), #让右侧侧边栏与容器对齐 #左侧侧边栏内容 sidebar = sidebar( width = 400, position = "left", open = "open", p("left sidebar contents, will be an assortment of input widgets"), p("if really tall, the contents shrink the height of the title above, up to some minimum, and then the sidebar will have a scrollbar, which i'm fine with"), p("but maybe instead of a scroll bar, i'd like the entire app to scroll down, but then i guess i wouldn't use a page_fillable"), p("anyways, when sufficiently filled with content, the title above squishes down nicely and looks good"), p("however, when i collapse the sidebar, then the title above expands to fill half the vertical space of the app") ), #右侧侧边栏组件 layout_sidebar( #右侧侧边栏内容 - 添加overlay = TRUE开启覆盖模式 sidebar = sidebar( width = 800, position = "right", open = "closed", overlay = TRUE, #侧边栏内容 p("right sidebar contents, can this sidebar open without squishing the main panel content, instead just covering it up until closed, as if the content here is just a reference to peek at periodically and then keep hidden usually?") ), #主内容区 layout_columns( # gap = 25, # padding = c(25, 25, 25, 25), col_widths = breakpoints( sm = c(12, 12, 12), #小屏:3行,每行12列 md = c(6, 6, 12), #中屏:2行,前两列各6,第三列12 lg = c(4, 4, 4) #大屏:1行,三列各4 ), p("contents 1"), p("contents 2"), p("contents 3") ) ) ) ), card_footer( "This is the footer, its size stays fixed... me likey" ) ) ) server <- function(input, output, session) { bs_themer() } shinyApp(ui = ui, server = server)
额外说明
- 页面滚动需求:如果希望整个页面滚动而非侧边栏内部滚动,只需替换
page_fillable为普通的page_fluid,内容超出视口时会触发全局滚动。 - 所有修改均基于bslib/Bootstrap内置功能,未添加自定义CSS,符合学习需求。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

