Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sticky header on a thead

Tags:

html

css

I have a table that can become come very long on the page so the header gets lost and so I thought a sticky header would fix that. You scroll down too far and the header is still there to let you know what the fields are.

I know the traditional ways of doing a sticky header with jQuery, but I wanted to try a different way with just css.

I found this on the web and it is supposed to work, but I cannot seem to make it do what it is supposed to.

.sticky {
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -ms-sticky;
  position: -o-sticky;
  top: 15px;
}

and help would be great or any other css tricks to help this work would be great.

I set up a jsFiddel over here of what my form looks like so you can get a good idea of what is happening.

like image 690
zazvorniki Avatar asked Jan 08 '14 18:01

zazvorniki


People also ask

How do you stick a header in CSS?

Answer: Use CSS fixed positioning You can easily create sticky or fixed header and footer using the CSS fixed positioning. Simply apply the CSS position property with the value fixed in combination with the top and bottom property to place the element on the top or bottom of the viewport accordingly.


2 Answers

Unless there is a bug in Chrome you can't fix the thead directly. Therefore you have to fix it on the th element:

thead th {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    background: white;
    z-index: 10;
}
like image 68
Jules Avatar answered Sep 28 '22 18:09

Jules


Take a look at this answer. The magic is in the position: fixed.

If you want to jump the gun: working example here

EDIT

I don't think you can do this cleanly without Javascript. Yet, I was intrigued by the problem, so I made this solution. It uses a wrapper div around the data with overflow: scroll.

JSFIDDLE

like image 20
Benjamin Avatar answered Sep 28 '22 19:09

Benjamin