Robin Elvin Robin Elvin - 6 months ago 21
CSS Question

Make HTML table expand to hold contents with no wrapping

I have a table which is currently 100% of the window width.

Sample structure: (CSS/styles removed for clarity)

<table>
<tbody>
<tr>
<td>Row ID</td>
<td><div>Some content</div><div>Another</div>...and so on
</tr>
</tbody>
</table>


Inside each second table cell per row are DIVs containing rows of text. At the moment when the table is rendered the DIV elements flow to the edge of the table and then wrap when they cannot fit.

What I need is these DIV elements to keep in a single row flowing off the screen. I can simulate by manually setting the table width to a large value e.g. 400% but this is often too wide. I need a way to make the table expand to contain the widest row but no larger. Using
white-space: nowrap
only wraps the text within each DIV.

Is there a way to do this with CSS?

Answer

You can add display: inline-block on div and white-space: nowrap on td

table {
  width: 100%;
}
td {
  border: 1px solid black;
  white-space: nowrap;
}
div {
  display: inline-block;
}
<table>
  <tbody>
    <tr>
      <td>Row ID</td>
      <td>
        <div>Some content</div>
        <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, magnam!</div>
        <div>Another</div>
        <div>Another</div>
        <div>Another</div>
    </tr>
  </tbody>
</table>

Comments