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

如何在Ag-Grid表格自适应高度时固定表头?

Fix for Ag-Grid Header Sticking to Top When Table Exceeds Viewport Height

Hey there! I’ve dealt with this exact scenario in Ag-Grid before, so let me share the most reliable fixes to keep your header pinned at the top when scrolling.

The simplest and most built-in way to get a fixed header is to let Ag-Grid handle internal scrolling instead of relying on page-level scrolling. Here’s how:

  • Remove the autoHeight configuration from your grid options. This setting makes the table expand to fit all rows, which triggers page scrolling instead of table-internal scrolling.
  • Set a fixed height for your grid container that fits within the viewport. You can use viewport units or calculate it to account for other page elements (like navigation bars or footers):
    const gridOptions = {
      // Adjust the subtracted value based on your page's top/bottom elements
      height: 'calc(100vh - 100px)',
      // Add your other grid configs (columnDefs, rowData, etc.) here
    };
    

When your row count exceeds the table’s fixed height, Ag-Grid will automatically add a scrollbar to the row body while keeping the header fixed at the top of the table container.

Option 2: CSS Sticky Header (For Auto-Height Scenarios)

If you need to keep autoHeight enabled but still want the header to stick during page scrolls, you can use CSS position: sticky. Note this works best if your grid container doesn’t have overflow: hidden set:

Add this to your stylesheet:

.ag-header {
  position: sticky;
  top: 0;
  z-index: 100; /* Ensures the header stays above other page content */
  background-color: white; /* Match your header's background to avoid transparency issues */
}

Just be aware this might have edge cases with Ag-Grid’s internal layout (like grouped columns or floating filters), so test thoroughly.

Why Your Original Auto-Height Setup Causes the Issue

When you use autoHeight: true, Ag-Grid expands to fit all rows. If the total table height exceeds the viewport, scrolling happens at the page level—not inside the grid. Since the header is part of the table’s normal flow, it scrolls along with the rest of the page. By switching to a fixed height, you force the grid to handle scrolling internally, which locks the header in place.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:39:18