How do you add sticky headers to Blazorise DataGrid?

Viewed 1429

Recently I had a request to add Sticky Header Functionality to a DataGrid in one of my Blazor Server Projects. I am using Blazorise and didn't see any existing features for sticky headers and found limited information online so I figured I'd document my solution.

1 Answers

I will preface my answer with the fact that this solution was built for chrome and may need to be tweaked for different browsers.

To start I added a sticky-header class to my site.css file:

.sticky-header {
    position: sticky;
    top: 0;
    z-index: 10;
}

    .sticky-header::before {
        content: '';
        width: 100%;
        height: 1px;
        position: absolute;
        top: -1px;
        left: 0;
        background-color: #fcfcfc;
        z-index: -1;
    }

    .sticky-header + .sticky-header::after {
        content: '';
        width: 1px;
        height: 100%;
        position: absolute;
        top: 0;
        left: -1px;
        background-color: #fcfcfc;
        z-index: -1;
    }

A couple of notes about the css. top is set to 0 to set the headers to the top of the screen and z-index just needs to be set to a higher index then the surrounding elements so that it will stay in front of the other elements.

Additionally I noticed that position: sticky got rid of my borders and as a result I utilized the ::before and ::after pseudo classes to help act like a internal border but this part of the code isn't necessarily required for sticky headers to work.

Once you have the above css, you will want to add it to your DataGrid. For Each DataGridColumn that you define in the DataGridColumns section you will want to add the following code:

<DataGrid>
   <DataGridColumns>
      <DataGridColumn HeaderCellClass="sticky-header" TItem="TEntity" Field="@nameof(TEntity.SomeProperty)" Caption="Some Caption" />
   </DataGridColumns>
</DataGrid>
Related