Search code examples
csshtml-tablefixed-header-tables

Set the first tr to fixed without losing the width


this is my fiddlejs: [https://jsfiddle.net/uj8gbeL1/]

Im trying to make fixed the first row of the table, but when i try to set the style postion:fixed, this row has a different width

How can i fix this issues without setting a "static" width to every th element?


Solution

  • You will solve this by using: <tr class="globalTr" style="position:sticky;top:0;z-index:1">

    Or better, put it in the css:

    .globalTr:first-child {
        position: sticky;
        top: 0;
        z-index: 1; 
    }
    

    However, your code could be formatted a lot better.
    Here is an example, please read the comments in the html:

    div {
      width: 100%;
      height: 200px;
      overflow: auto;
    }
    
    table {
      font-family: sans-serif;
      border-collapse: collapse;
    }
    
    thead {
      position: sticky;
      top: 0;
      z-index: 1;
    }
    
    th, td {
      border: 1px solid #369;
      padding: 10px;
    }
    
    th {
      background: #369;
      color: white;
    }
    
    td {
      background: aliceblue;
    }
    <div>
      <table>
        <thead>
          <tr>
            <th>Heading1</th> <!-- th is for headings -->
            <th>Heading2</th>
          </tr>
        </thead>
        <!-- use thead and tbody -->
        <tbody>
          <tr>
            <td>Content</td> <!-- td is for cells -->
            <td>Content</td>
          </tr>
          <tr>
            <td>Content</td>
            <td>Content</td>
          </tr>
          <tr>
            <td>Content</td>
            <td>Content</td>
          </tr>
          <tr>
            <td>Content</td>
            <td>Content</td>
          </tr>
          <tr>
            <td>Content</td>
            <td>Content</td>
          </tr>
          <tr>
            <td>Content</td>
            <td>Content</td>
          </tr>
        </tbody>
      </table>
    </div>