Michi
Michi

Reputation: 1

How to make head of css table sticky

I have a css table, the first 2 columns are already sticky and everything works fine, but I want the table head to be sticky as well.I just cant make it work.

I have already tried using a class for every with: position: sticky, top: 0.

this code makes the first 2 columns sticky

table {
    table-layout: fixed;
    width: 100%;
}
.fixed{
    position: sticky;
    left: 0;
}
.fixed2 {
    position: sticky;
    left: 120px;
}

what I want is the thead to be sticky as well.

Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 112

Answers (2)

Pankaj Divgi
Pankaj Divgi

Reputation: 76

css

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

html

<table class="table">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">First</th>
                <th scope="col">Last</th>
                <th scope="col">Handle</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th scope="row">1</th>
                <td>Mark</td>
                <td>Otto</td>
                <td>@mdo</td>
            </tr>
        </tbody>
    </table>

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Give table-fixed class to table tag and try this:

.table-fixed{
  width: 100%;
  tbody{
    height:200px;
    overflow-y:auto;
    width: 100%;
    }
  thead,tbody,tr,td,th{
    display:block;
  }
  tbody{
    td{
      float:left;
    }
  }
  thead {
    tr{
      th{
        float:left;
      }
    }
  }
}

Upvotes: -1

Related Questions