WoJ WoJ - 1 month ago 4
CSS Question

How to make a tight cell around text and expand empty ones?

I would like to build a

table
which has four columns: two with text and two empty. I want the empty ones to expand as much as possible and the ones with text to be tight.

The following snippet shows such a table: the widths of the columns are probably weighted with the size of the text inside.



table,
td {
border: solid;
border-collapse: collapse;
}

<table style="width: 100%">
<tr>
<td>This is some text</td>
<td>And some more</td>
<td></td>
<td></td>
</tr>
</table>





What could be done to turn this into a table like

enter image description here

where the text would be tightly surrounded by the cell and the empty ones expanded?

Answer

If a flexbox is an option, you can do this:

  1. Give display: flex to the tr

  2. Give flex: 1 to the two empty ones.

See demo below:

table,
td {
  border: solid;
  border-collapse: collapse;
}
table tr {
  display: flex;
}
td:nth-last-child(1),
td:nth-last-child(2) {
  flex: 1;
}
<body>
  <table style="width: 100%">
    <tr>
      <td>This is some text. This is some text</td>
      <td>And some more</td>
      <td></td>
      <td></td>
    </tr>
  </table>
</body>