Can you make a table header sticky within a scrolling div using \'position: sticky\'?

DDD
Release: 2024-10-29 19:55:02
Original
538 people have browsed it

Can you make a table header sticky within a scrolling div using 'position: sticky'?

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; }
Copy after login

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>
Copy after login

For multiple rows in the 'thead', use this to maintain stickiness on the first row:

thead tr:first-child th { position: sticky; top: 0; }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!