Sticky Headers within Scrolling Table Divs
With the recent introduction of 'position: sticky' into Webkit, developers are exploring its potential uses. One question that arises is whether it can be employed to maintain the header (thead) of a table within a scrolling div.
Concept
By default, 'position: sticky' limits its functionality to the parent element, making it unsuitable for this specific scenario. However, it is possible to leverage 'sticky-positioning' to achieve the desired effect.
Solution
To make the table header sticky within the scrolling div, you can append the following line in your stylesheet:
thead th { position: sticky; top: 0; }
Ensure your table has the necessary 'thead' and 'th' elements to apply the styling.
Implementation
<table> <thead> <tr> <th>column 1</th> <th>column 2</th> <th>column 3</th> <th>column 4</th> </tr> </thead> <tbody> // your body code </tbody> </table>
For multiple rows in the 'thead', use this to maintain stickiness on the first row:
thead tr:first-child th { position: sticky; top: 0; }
Browser Support
As of March 2018, 'position: sticky' has widespread support across modern browsers: https://caniuse.com/#feat=css-sticky
Credit
This solution was initially proposed by @ctf0 in a comment on December 3, 2017.
The above is the detailed content of Can you make a table header sticky within a scrolling div using \'position: sticky\'?. For more information, please follow other related articles on the PHP Chinese website!