Matt
Matt

Reputation: 1570

Responsive horizontal scrolling table with fixed columns

I'd like to create a table that has two fixed columns, left and right and a horizontally scrollable section in the middle. An issue is that because the table is responsive, a width value can't be provided for the overflow and there could be any number of columns or rows.

See the mockup here - the middle section scrolls but the two columns on the left and right stay fixed.

enter image description here

I've already tried this by floating three different tables together but this is messy and very hard to maintain.

<table>
    <thead>
        ...
    </thead>
    <tbody>
        ...
    </tbody>
</table>
<div class="scrollable-section">
    <table>
        <thead>
            ...
        </thead>
        <tbody>
            ...
        </tbody>
    </table>
</div>
<table>
    <thead>
        ...
    </thead>
    <tbody>
        ...
    </tbody>
</table>

Basically, I'd like to achieve this inside one table and I don't mind any added bits of JavaScript if neccessary using this markup:

table {
  position: relative;
  width: calc(100% - 200px);
  margin-left: 100px;
}

table {
  overflow-x: scroll;
}

table th {
  background: #333;
  color: #fff;
  padding: 12px;
}

table td:first-of-type, table th:first-of-type {
/* fixed left column */
  position: absolute;
  left: -100px;
  width: 100px;
  
}

table td:last-of-type, table th:last-of-type {
/* fixed right column */
  position: absolute;
  right: -100px;
  width: 100px;
}
<table>
    <thead>
        <tr>
            <th>Row titles</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th>Title</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row title</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td><button>Do something</button></td>
        </tr>
        <tr>
            <td>Row title</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td><button>Do something</button></td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Views: 4493

Answers (1)

Ravi Ubana
Ravi Ubana

Reputation: 395

You can try datatable logic, there are some good contributions already available.

Upvotes: 0

Related Questions