Angular Material中md-tab-group内md-tabs滚动无法固定的问题
Got it, let's sort out why your tabs aren't staying fixed when scrolling. The core issue is that you're applying position: fixed directly to the <md-tab> element—and that doesn't work because Angular Material's Tabs component renders the tab headers into a separate internal container (like .mat-tab-header), so your style isn't targeting the right part of the component.
Here's how to fix it properly:
Solution 1: Wrap the Tab Group in a Fixed Container
First, adjust your HTML to wrap the <md-tab-group> in a dedicated container, then apply fixed positioning to that container:
<!-- Add a fixed container around your tab group --> <div class="fixed-tabs"> <md-tab-group> <md-tab label="{{category}}" *ngFor="let category of itemCategory"> <!-- Your tab content goes here --> </md-tab> </md-tab-group> </div> <!-- Make sure your main content has top margin to avoid being hidden under the fixed tabs --> <div class="page-content"> <!-- Rest of your page content --> </div>
Then update your CSS:
.fixed-tabs { position: fixed; top: 0; left: 0; right: 0; z-index: 100000000; background-color: #fff; /* Critical: prevents page content from showing through tabs on scroll */ } .page-content { margin-top: 48px; /* Match this to the height of your tabs (Angular Material tabs default to ~48px) */ }
Solution 2: Target Angular Material's Internal Header Element
If you don't want to add an extra container, you can directly target the .mat-tab-header element that Angular Material generates for the tab headers:
.mat-tab-header { position: fixed; top: 0; left: 0; right: 0; z-index: 100000000; background-color: #fff; } /* Adjust the tab body wrapper to avoid overlap */ .mat-tab-body-wrapper { margin-top: 48px; }
Why Your Original Code Didn't Work
When Angular Material renders the Tabs component, it takes the label content from each <md-tab> and moves it into a centralized .mat-tab-header container. Your position: fixed on <md-tab> was targeting a hidden part of the component, not the visible tab headers—so it had no effect on the actual tab bar you see.
Additional Notes
- If you already have a fixed header (your
.q-header), adjust thetopvalue of the tabs (e.g.,top: 40px) to avoid overlapping with it. - Double-check the
z-indexvalues to ensure the tabs stay above other page content. - Test the margin-top value on your content—you might need to tweak it based on your tab bar's actual height.
内容的提问来源于stack exchange,提问作者Mrugesh

