How to create a table with fixed header and scrollable body ?
The purpose of this article is to create a table with a fixed header and scrollable body. We can create such a table with either of the two approaches.
- By setting the position property to “sticky” and specifying “0” as a value of the top property for the <th> element.
- By setting the display to “block” for both <thead> and <tbody> element so that we can apply the height and overflow properties to <tbody>.
Note:
- The position property states the type of positioning for an element.
- The display property states that how an element should be displayed.
Example: Below is the code which illustrates the formation of table with position property.
HTML
<!DOCTYPE html><html> <head> <style> .fixTableHead { overflow-y: auto; height: 110px; } .fixTableHead thead th { position: sticky; top: 0; } table { border-collapse: collapse; width: 100%; } th, td { padding: 8px 15px; border: 2px solid #529432; } th { background: #ABDD93; } </style></head> <body> <div class="fixTableHead"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html> |
Output:

Example 2: Below is the code which illustrates the formation of table with display property.
HTML
<!DOCTYPE html><html> <head> <style> .tableFixHead { width: 500px; table-layout: fixed; border-collapse: collapse; } .tableFixHead tbody { display: block; width: 100%; overflow: auto; height: 50px; } .tableFixHead thead tr { display: block; } .tableFixHead th, .tableFixHead td { padding: 5px 10px; width: 200px; } th { background: #ABDD93; } </style></head> <body> <div class="tableFixHead"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html> |
Output:






Please Login to comment...