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

如何在页面顶部创建固定tabPanel横幅并使下方内容可滚动?

实现Shiny页面中tab标签栏固定+内容区域滚动的效果

要实现tab标签栏固定在页面顶部、仅内容区域滚动的效果,直接通过自定义CSS调整元素定位即可,以下是修改后的完整可运行代码:

library("shiny")
library("stringi")

txt <- paste(sapply(seq_len(100), function(x){
  p <- shiny::tags$p(stringi::stri_rand_lipsum(1))
  return(as.character(p))
}), collapse = "")


ui = navbarPage(title = "Navbar example", 
                position = c("fixed-top"),
                id = "navbar",
                # 添加自定义CSS
                tags$style(HTML("
                  /* 给body设置顶部内边距,避开固定的navbar */
                  body {
                    padding-top: 50px;
                  }
                  /* 固定tab标签栏 */
                  .fixed-tabset .nav-tabs {
                    position: fixed;
                    top: 50px; /* 对应navbar的高度,确保标签栏接在navbar下方 */
                    left: 0;
                    right: 0;
                    background-color: #fff; /* 背景色覆盖下方内容 */
                    border-bottom: 1px solid #ddd;
                    z-index: 1000;
                  }
                  /* 设置内容区域的布局,让它可滚动 */
                  .fixed-tabset .tab-content {
                    margin-top: 80px; /* 避开固定的标签栏,值要大于等于标签栏高度 */
                    overflow-y: auto;
                    height: calc(100vh - 80px); /* 内容区域占满剩余视口高度 */
                  }
                ")),
                tabPanel(title = "tab 1", 
                         # 给tabsetPanel添加自定义类
                         tabsetPanel(id = "id1", class = "fixed-tabset",
                                     tabPanel(title = "A",
                                              HTML(txt)
                                     ),
                                     tabPanel(title = "B",
                                              HTML(txt)
                                     )
                         )),
                tabPanel(title = "tab 2", 
                         tabsetPanel(id = "id2", class = "fixed-tabset",
                                     tabPanel(title = "C",
                                              HTML(txt)
                                     ),
                                     tabPanel(title = "D"),
                                     tabPanel(title = "E",
                                              HTML(txt)
                                     )
                         ))
)

server = shinyServer(function(input, output) {
})

shinyApp(ui, server)

关键说明

  • 给tabsetPanel添加了fixed-tabset类,方便CSS精准定位;
  • 通过position: fixed把tab标签栏固定在navbar下方,设置背景色避免被内容滚动覆盖;
  • 内容区域设置overflow-y: auto开启垂直滚动,用calc(100vh - 80px)让内容区域自动适配剩余视口高度;
  • 用body的padding-top替代原有的多个br(),布局更规范可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:55:29