Html – Make Table Width 100% with Last Column Filling Remainder without squashing other columns content/width

csshtmlhtml-table

Is it possible to make a table (which will have dynamically created text) to have for example:

table width 100% of the screen
5 columns
last column is empty ( )
the first four columns have text and their width is dynamic
the last column is remainder of the width
without squashing the text in the first four columns

I have this so far and it squashes the text which is what I'm trying to avoid:

<table style="width:100%;" border="1">
<tr>
    <td>One Two Three</td>
    <td>Two Three Four</td>
    <td>Three Four Five</td>
    <td>Four Five Six</td>
    <td style="width:100%;">&nbsp;</td>
</tr>
</table>

I can't use "white-space: nowrap" as I do want the text to wrap if there's enough text.

Edit: "I'd just like the [first four] columns to be the width they would be if I removed the width attribute from the table tag. But still have the table be 100% of the width of the page."

Any ideas? CSS solutions preferable!

Best Answer

You can use flexbox to accomplish this

CSS

table {
    width:100%;
    border: 1px solid black;
    border-collapse: collapse;
}
td + td {
    border-left: 1px solid black;
}
tr {
    display: flex;
    align-items: stretch;
}
td:last-child {
    flex: 1;
    background: yellow;
    display:inline-block;
    /* to keep IE happy */
}

FIDDLE (Resize the browser window to see this in action)

table {
  width: 100%;
  border: 1px solid black;
  border-collapse: collapse;
}
td + td {
  border-left: 1px solid black;
}
td:last-child {
  background: yellow;
}
<table>
  <tr>
    <td>One Two Three</td>
    <td>Two Three Four</td>
    <td>Three Four FiveThree Four FiveThree Four FiveThree Four FiveThree Four Five</td>
    <td>Four Five Six</td>
    <td>&nbsp;f</td>
  </tr>
</table>

NB:

IE 10-11 has an issue that Inline elements (and apparently table-cells as well) are not treated as flex-items.

This issue is documented by Phillip Walton here and the workaround (from the above post) is:

This issue can be avoided by adding a non-inline display value to the items, e.g. block, inline-block, flex, etc.


Btw: the following is what the same fiddle above looks like without using flexbox - Notice that the last td doesn't actually fill up the remaining space, but rather takes up it's own natural space - which is what the OP did NOT want.