[ HTML / CSS ]
To set a fixed header on a table you just have to keep in mind two things: you are going to work with two (or more) different tables and those tables’ tds/ths width (or the result of it) must be the same.
So the next question is: am I going to work with fixed widths? No, but it depens on the occasion.
CASE 1: You need a table knowing your data, so, for example, you know that you’ll need just 2 columns (for example extracting data from any database table with 2 columns: ‘ID’ and ‘Name’).
Let build the table (I’m not explaining here how to get data from the db, I’m just building the HTML table):
ID | Name |
---|---|
1 | John |
2 | Smith |
Now, if we imagine we’ll have hundreds of results (<tr> in <tbody>) and we always want to show the table header,
First, separate thead and tbody in two different tables and set the tbody table into a div:
ID | Name |
---|
1 | John |
2 | Smith |
Now, we need some CSS:
table { width:100%; } th, td { min-width:20px; width:20px; max-width:20px; } div.tbody1 { overflow-y:auto; height:500px; max-height:500px; }
Now we have a table with fixed header and a body that scroll if results are a lot. I’ve set to 20px min and max the width of ths and tds, and to 100% the width of the tables to make the browser set automatically the width of each element, mantaining the same proportions between the two tables’ elements. (Note: if you try to set manually the width of any of the td or th, different from 20px, the table won’t show properly)
Later I’ll explain how to make a table with a lot of th good to see, playing with PHP, Javascript and, oviously, CSS.