nowox
nowox

Reputation: 29116

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.

Upvotes: 5

Views: 15083

Answers (2)

Mostafa Soufi
Mostafa Soufi

Reputation: 799

You can also autoresize and make it autofit by table-layout

table {
    table-layout: auto;
}

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 273379

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>

Upvotes: 8

Related Questions