Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed table layout, but one column adjusting to content? (HTML and CSS only)

In the snippet below, is it possible to get label column to adjust to its content? Currently it receives no width at all :(.

For this question I am only interested in possible solutions that use HTML tables and CSS, without the help of Javascript libraries.

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

td { border: 1px solid black; margin: 0px; padding: 0px; }

input[type='text'] { width: 100%; box-sizing: border-box; }
<table>
<tr>
  <td style="width: 100%;"></td>
  <td style="width: auto;">Label:</td>
  <td style="width: 5px;"></td>
  <td style="width: 200px;"><input type='text' /></td>
  <td style="width: 100%;"></td>
</tr>
</table>

Context: I am used to program desktop application grid layouts that consist of growing columns, fixed-width columns and columns that adjust to the preferred size of the content. Usually it is also possible to provide resize weights for the growing columns.

like image 795
Reto Höhener Avatar asked Dec 04 '25 07:12

Reto Höhener


2 Answers

Well, just make sure that sum of all columns width is no more than 100%. width: auto sets width of whatever space is left, but there's nothing left when other columns takes >100% of width.

Try this:

<table class="t">
  <tr>
    <td style="width: 40%;">a</td>
    <td style="width: auto;">b</td>
    <td style="width: 50px;">c</td>
    <td style="width: 40%;">d</td>
  </tr>
</table>

If table width is 1000px, then 1% of width is 10px. In that case 40% takes 400px, 50px takes... 50px, and auto takes what's left, which is (1000px - 400px - 400px - 50px) == 150px.

If you had 2 columns with width: auto, then these columns width would be 75px, because 150px (space left) / 2 (number of columns width: auto) == 75px.

If I had 4 columns with widths: 50%, 50%, 50px, auto, then no matter how wide table is, the space left is kind of -50px (which is what makes width: auto look like width: 0).

Make sure your "space left" is more than 0. One column with width: 100% and you're out of it.

like image 139
kamyl Avatar answered Dec 05 '25 23:12

kamyl


Looks like CSS grid does exactly what I was looking for:

.container {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr auto 5px 200px 1fr;  
  border: 1px solid black;
  border-width: 1px 0 0 1px; // top + left
}

.container > DIV { 
  border: 1px solid black;
  border-width: 0 1px 1px 0; // right + bottom
}

input[type='text'] { width: 100%; }
<div class="container">
  <div></div>
  <div>Label:</div>
  <div></div>
  <div><input type='text' /></div>
  <div></div>
</div>
like image 33
Reto Höhener Avatar answered Dec 05 '25 23:12

Reto Höhener