Search code examples
htmlcsshtml-table

Fit content and auto width in HTML table


In the following example, I would like my table to have column width customized :

  1. Column width fits the content
  2. Takes the remaining space
  3. Column width fits the content
  4. Fixed column width

table {
    width: 300px;
    border: 1px solid red;
}

td {
    border: 1px solid blue;
    padding: 0px;
    margin: 0px;
    min-width: 0px;
}

tr td:nth-child(1) { width: fit-content; }
tr td:nth-child(2) { width: auto; }
tr td:nth-child(3) { width: fit-content; }
tr td:nth-child(4) { width: 50px; }

tr th:nth-child(1) { width: fit-content; }
tr th:nth-child(2) { width: auto; }
tr th:nth-child(3) { width: fit-content; }
tr th:nth-child(4) { width: 50px; }
<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<table>

Unfortunately, it doesn't quite work.


Solution

  • Use a small value (different from 0) to have the fit-content behavior:

    table {
        width: 300px;
        border: 1px solid red;
    }
    
    td {
        border: 1px solid blue;
        padding: 0px;
        margin: 0px;
        white-space:nowrap; /* in case you have long content */
    }
    
    tr td:nth-child(1) { width: 1px; }
    /*tr td:nth-child(2) { width: auto; } not needed */
    tr td:nth-child(3) { width: 1px; }
    tr td:nth-child(4) { width: 50px; }
    
    tr th:nth-child(1) { width: 1px; }
    /*tr th:nth-child(2) { width: auto; } not needed  */
    tr th:nth-child(3) { width: 1px; }
    tr th:nth-child(4) { width: 50px; }
    <table>
    <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
    <th>4</th>
    </tr>
    <tr>
    <td>a a a</td>
    <td>b</td>
    <td>c</td>
    <td>d</td>
    </tr>
    <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
    </tr>
    <table>