How do you make one column with a fixed width and another one with auto width in <table> using css?

56 views Asked by At

I am making a table with resizable columns and facing an issue I cannot resolve. I need to enable a user to drag the side of a column to resize it and reset the width if they want to. By resizing it, the user changes the width of each column in a table with table-layout set to fixed which works perfect but I cannot implement the reseting.

When a user resets one particular column it should be reset to the width of its content (meaning the width of its largest cell, the thing you get if you set table-layout to auto). I don't understand how to achieve it preserving the width of other columns.

For example, if there are two columns: A and B. With table-layout set to auto, A is 200px in width and B is 250px in width. The user cannot resize the columns with table-layout set to auto because the width of a column won't go below its minimum, so I set table-layout to fixed. Now the user can resize them, say, to 100px for A and 150px for B. What should I do when the user wants to reset the column B to match the width of its content? I cannot set table-layout back to auto because it would affect the column A. I also cannot set the width of B back to 250px because, possibly, the content could have changed by the user. I cannot set width to auto because it doesn't work with table-layout being fixed.

All I can think of is, using js, set table-layout to auto, get the width of the column B and save it, switch table-layout back to fixed and set the column B to the saved width. But, come on, this solution does not look any good.

If that helps, I am using the table from ant-design

1

There are 1 answers

3
Mahesh Prajapati On

As per your requirement I have created an example I hope this HTML table structure will be useful for you.

table {
          border-collapse: collapse;
          table-layout: fixed;
          width: 100%;
        }

        table th{
            background-color: antiquewhite;
        }
      
        table, th, td {
          border: 1px solid #000; /* Add a 1px border to the table, th, and td elements */
          padding: 10px;
        }
<table id="resizable-table">
        <colgroup>
          <col style="width: 100px;" />
          <col style="width: auto;" />
          <col style="width: 150px;" />
        </colgroup>
        <thead>
          <tr>
            <th>Column A</th>
            <th>Column B</th>
            <th>Column C</th>
          </tr>
        </thead>
        <tbody>
            <tr>
                <td>Column A</td>
                <td>Column B</td>
                <td>Column C</td>
            </tr>
        </tbody>
      </table>