Search code examples
htmlcsshtml-table

Position a button on the right of each row with overflow-x


I want to add a button next to each row of my table. Plot twist, the table is inside a div with a fixed width and overflow-x for responsiveness. I want the button to show next to each row outside the container div.

With my current code, the button does show up next to the row but stays in the fixed div.

<div style="width:100px; overflow-x: scroll;">
  <table>
    <thead>
      <tr>
        <th>ID</th><th>ID</th><th>ID</th><th>ID</th><th>ID</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td>
        <td>
          <div style="position:relative; width:0px;">
            <button style="position:absolute;left:10px;">Edit</button>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>


Solution

  • The solution is using position sticky on the last column.

    position: sticky; right: 0px
    

    Reference : W3 Schools.

    Here's the snippet:

    <div style="width:100px; overflow-x: scroll;">
      <table>
        <thead>
          <tr>
            <th>ID</th><th>ID</th><th>ID</th><th>ID</th><th>ID</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td>
            <td style="position: sticky; right: 0px">
              <button>Edit</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>