htmlcsstailwind-css

CSS looking like table with fixed header and left column


I need to create something looking like table, so we have cells. The problem is, i need to first "column" and first "row" will be fixed, so when i scroll vertically or horizontally that parts are all time visible.

In other worlds, i want something working looking excel/opencalc where you can move cells, but header and left side are always on same place.

The max result I reach (tailwind):

  <div class="h-32 w-full flex">
    <div class="bg-gray-600 w-64">
      Task
    </div>
    <div class="flex-1 flex overflow-hidden">
      <div class="flex-1 overflow-y-scroll flex">
        <div class="h-full min-w-64 max-w-64">
          testa
        </div>
      </div>
    </div>
  </div>

So is almost that, but every row is separated (separate scroll).


Solution

  • you need a combination of position: sticky for the fixed parts and proper styling for the table and its content

    <div class="relative h-96 w-full overflow-auto">
      <table class="min-w-full border-collapse table-fixed">
        <thead>
          <tr>
            <th class="bg-gray-600 text-white p-4 sticky top-0 z-10">Header 1</th>
            <th class="bg-gray-600 text-white p-4 sticky top-0 z-10">Header 2</th>
            <th class="bg-gray-600 text-white p-4 sticky top-0 z-10">Header 3</th>
            <th class="bg-gray-600 text-white p-4 sticky top-0 z-10">Header 4</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td class="bg-gray-200 text-black p-4 sticky left-0">Row 1 Col 1</td>
            <td class="bg-white p-4">Row 1 Col 2</td>
            <td class="bg-white p-4">Row 1 Col 3</td>
            <td class="bg-white p-4">Row 1 Col 4</td>
          </tr>
          <tr>
            <td class="bg-gray-200 text-black p-4 sticky left-0">Row 2 Col 1</td>
            <td class="bg-white p-4">Row 2 Col 2</td>
            <td class="bg-white p-4">Row 2 Col 3</td>
            <td class="bg-white p-4">Row 2 Col 4</td>
          </tr>
          <tr>
            <td class="bg-gray-200 text-black p-4 sticky left-0">Row 3 Col 1</td>
            <td class="bg-white p-4">Row 3 Col 2</td>
            <td class="bg-white p-4">Row 3 Col 3</td>
            <td class="bg-white p-4">Row 3 Col 4</td>
          </tr>
        </tbody>
      </table>
    </div>