Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position sticky on thead

Tags:

html

css

As you might know, position: sticky; has landed in Webkit (demo). So far I can see this only works within the parent element. But I'd like to know if I can use this in a scrolling div with a table.

So it needs to 'listen' on the scrolling event of the div, not the table.

I know I can do this with javascript and absolute positioning, but I was wondering if the sticky-positioning would support this.

like image 965
Willem de Wit Avatar asked Sep 04 '12 15:09

Willem de Wit


People also ask

How do I make the position sticky on Thead th?

Position sticky on thead th works in 2018! In your stylesheets just add this one line: thead th { position: sticky; top: 0; } Your table will need to include thead and th for this to style.

Why can’t I use <Thead> and <TR> for stickiness?

The issue boils down to the fact that stickiness requires position: relative to work and that doesn’t apply to <thead> and <tr> in the CSS 2.1 spec. There are two very extreme reactions to this, should you need to implement sticky table headers and not be aware of the <th> workaround.

What is sticky positioning?

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned. This is the demo from MDN. CSS position: sticky is supported in Firefox, Safari, and Chrome Canary (56+).

How to make a Thead header sticky?

Also, if you have multiple rows in thead, you can select the first one to remain sticky: If you need sticky header for chrome only then you can set position: sticky; top: some_value (top property is mandatory) for td element in a thead element. See: This is the better answer imo.


1 Answers

Position sticky on thead th works in 2018!

In your stylesheets just add this one line:

thead th { position: sticky; top: 0; } 

Your table will need to include thead and th for this to style.

<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> 

Also, if you have multiple rows in thead, you can select the first one to remain sticky:

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

As of March 2018 support is pretty much there across modern browsers ref: https://caniuse.com/#feat=css-sticky

Credit goes to @ctf0 for this one (ref comment made 3 Dec 2017)

like image 73
Evolve Avatar answered Sep 22 '22 16:09

Evolve