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

如何让DT组件的Caption标题始终相对于mainPanel宽度居中显示

解决方案

问题根源:开启scrollX = TRUE后,宽表的实际渲染宽度远大于mainPanel的可视宽度,DT组件的caption默认跟随表格实际宽度居中,因此在侧边栏展开时会出现偏移。
你只需要修改caption的样式,添加width: inherit属性,让caption继承外层DT容器的宽度,即可实现无论侧边栏是否折叠,标题始终相对于mainPanel居中:

output$panel1_data <- DT::renderDT(server = FALSE, {
    DT::datatable(xyz_query,
                  extensions = c('Buttons'),
                  caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:black; font-size:150%; width: inherit;',
                                                     'MTCARS mtCARS mTcArS MTcars'),
                  options = list(scrollY = 600,
                                 scrollX = TRUE,
                                 dom =  '<"float-left"l><"float-right"f>rt<"row"<"col-sm-4"B><"col-sm-4"i><"col-sm-4"p>>',
                                 lengthMenu=  list(c(10, 25, 50, -1), 
                                                   c('10', '25', '50','All')),
                                 scrollCollapse= TRUE,
                                 lengthChange = TRUE, 
                                 widthChange= TRUE,
                                 rownames = TRUE))})

修改前的问题表现

  • 展开侧边栏时标题偏移:展开侧边栏显示效果
  • 折叠侧边栏时标题正常居中:折叠侧边栏显示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 01:09:00