kumara
kumara

Reputation: 937

sticky header with HTML table

I am trying to develop fix header html table. I use basic HTML and CSS for do it. But its not working. for do this, I search in google. I used below sample for do this. i applied correctly. but not working well resource

 
body{height:100px; overflow:scroll}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  height:300px;
}
th{position: sticky !important}
td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
  height:100px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
 
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>

</head>
<body>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
    <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>
</body>
</html>

when page scroll, i need to fix my table headers. how i do it? please check my sample

Upvotes: 0

Views: 1739

Answers (2)

Lisa
Lisa

Reputation: 293

thead {
    background-color: #f5f5f5;
    position: sticky;
    top: 0; /* Don't forget this, required for the stickiness */
}

Feel free to change the background colour it an example. This way it looks as though the entire heading row is moving as you scroll.

Upvotes: 0

Chaiya Tantisukarom
Chaiya Tantisukarom

Reputation: 51

You don't apply it correctly.

top: 0;

is the key to stick the, position:sticky, on top.

th {
  background: white;
  position: sticky;
  top: 0; /* Don't forget this, required for the stickiness */
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
}

Upvotes: 4

Related Questions