'Fit content and auto width in HTML table
In the following example, I would like my table to have column width customized :
- Column width fits the content
- Takes the remaining space
- Column width fits the content
- 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 1:[1]
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>
Solution 2:[2]
You can also autoresize and make it autofit by table-layout
table {
table-layout: auto;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Temani Afif |
Solution 2 | Mostafa Soufi |