css – Fix first row table


I need to pin the first row of my table always to the top of the page. I've read several questions about this same problem, but I couldn't solve it…

My code:

<table border="2px">

 <tr bgcolor="0099FF" id="topo">
      <th> ID </th>
      <th> Acertos Humanas </th>
      <th> Nota humanas </th>
      <th> Acertos Naturezas </th>
      <th> Nota Naturezas </th>
      <th> Acertos Linguagens </th>
      <th> Nota Linguagens </th>
      <th> Acertos Matematica </th>
      <th> Nota Matematica </th>
      <th> Soma acertos </th>
      <th> Soma notas </th>
      <th> Soma acertos(2) </th>
      <th> Redacao </th>
      <th> Media sem redacao </th>
      <th> Media com redacao </th>


$tudo = file('notas.txt');

for ($l=0; $l<90; $l++) {

    $cada_item[$l] = explode (" ", $tudo[$l]);

    $idd = $l+1;

    $cor = $l%2 !=0 ? "#D0D0D0" : "white"; 

    echo '<tr bgcolor="'.$cor.'"><td>'. $idd ."</td>";

      for ($i=0; $i<14; $i++) {
          echo "<td>". $cada_item[$l][$i] ."</td>";

    echo "</tr>";



I tried a number of things, but I preferred to take it out so as not to harm the code. I thought I just got the first tr in css and put position:fixed . And then another div wrapped around the other trs , that is, wrapped around the php tags. But the biggest problem is that the width of each cell in the table does not follow the width of the cells th and then everything is crooked because the width of the table is smaller than that of the first row…
I want to do this with css (I accept javascript solution in the second case, but without jquery, please) Thanks!


Yes, just use position:fixed and set a fixed width for the cells.

And you used repetition in php to set the colors of each line. It can also be done via css3 with the nth-child selector

table {
    border:1px solid #aaa;
    table-layout: fixed;
    box-sizing: border-box; 

tr:first-child {
    background: #0099FF;

th, td {

tr:not(:first-child):nth-child(odd) {
        <th>Acertos Humanas</th>
        <th>Notas Humanas</th>
        <th>Acertos Naturezas</th>
Scroll to Top