如何在Ag-Grid表格自适应高度时固定表头?
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.
Option 1: Use Fixed Table Height (Recommended)
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
autoHeightconfiguration 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

