0

i have two table headers and i want to sticky it using CSS only. Here is my html, and also posted image of my table, i have all the dynamic data and columns.

       <div class="fix-table-parent">
        <table>
            <thead>
                <tr class="first_head">
                    <th>test11</th>
                    <th>test12</th>
                    <th>test13</th>
                </tr>
                <tr class="second_head">
                    <th>test21</th>
                    <th>test22</th>
                    <th>test23</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                </tr>
                <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                </tr>
                <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                </tr>
            </tbody>
        </table>
    </div>

enter image description here

How can I make the headers sticky using only CSS?

Apurv Chaudhary
  • 1,672
  • 3
  • 30
  • 55
  • Can you elaborate on your question a little bit? Is your data static? How much data do you have to show and how many columns are there? – Dhaval Chheda Jan 09 '20 at 11:47
  • 1
    Does this answer your question? [CSS-Only Sticky Table Headers In Chrome](https://stackoverflow.com/questions/44001954/css-only-sticky-table-headers-in-chrome) – Laurent S. Jan 09 '20 at 11:48
  • @DhavalChheda my data and columns both are dynamic, and i posted one image of my table – Apurv Chaudhary Jan 09 '20 at 11:52
  • Oh ohk I get it, It is bit tricky since you cannot find any libraries that will do that. I had done that before but don't have the code, if it is alright with you I can give you an idea in the answer section. – Dhaval Chheda Jan 09 '20 at 12:07
  • @DhavalChheda yes please. – Apurv Chaudhary Jan 09 '20 at 12:33
  • You can create two similiar tables and superimpose on each other. For the top table set the visibility of data to hidden and for the behind table, set the z-index of header to maximum and the visibility of other data to hidden. So when u do this, the header of behind table which is static will always be present there but the data will be shown from the top table so you can scroll down. – Dhaval Chheda Jan 09 '20 at 13:16

1 Answers1

3

Try below css. You have to change top: 20px; with height of .first_head.

.fix-table-paren thead .first_head th{ position: sticky; top: 0; }
.fix-table-paren thead .second_head th{ position: sticky; top: 20px; }
Jignesh Panchal
  • 1,037
  • 11
  • 29
  • it's working fine but in my case some time **i have only one header** so in that case it was no working, and i can not put static **top: 20px** – Apurv Chaudhary Jan 09 '20 at 12:21