trs
trs

Reputation: 863

How to make table td take the width of its content

Demo: http://jsfiddle.net/zvmcyp4w/

.wide {
  width: 400px;
  background: lightblue;
}
.narrow {
  width: 200px;
  background: lightpink;
}
.table-responsive {
  max-width: 100%;
  overflow-x: auto;
}
table {
  border: 1px solid black;
  border-collapse: collapse;
}
td {
  border: 1px solid black;
  padding: 5px;
}

<div class="wide">
  <div class="table-responsive">
    <table>
      <tr>
        <td>Many words</>
        <td>word</td>
        <td>oneword</td>
        <td>onemoreword</td>
      </tr>
    </table>
  </div>
</div>

<div class="narrow">
  <div class="table-responsive">
    <table>
      <tr>
        <td>Many words</>
        <td>word</td>
        <td>oneword</td>
        <td>onemoreword</td>
      </tr>
    </table>
  </div>
</div>

I'm simulating a responsive layout with "wide" and "narrow" containing the same table.

In "narrow" you can scroll left and right.

If the content of a cell is made out of multiple words, like the first cell, it automatically breaks into lines.

What I'm looking for is to avoid breaking the line and have the cell expand horizontally to accommodate its content, given that the content is dynamic therefore no fixed widths or min-widths allowed.

Ideally a clean CSS only solution would be great, I already know how to solve it with JavaScript.

Upvotes: 0

Views: 976

Answers (3)

Alexandru Severin
Alexandru Severin

Reputation: 6228

So you want multiple words not to expand on multiple rows? You can use white-space property

.narrow table td{
    white-space:nowrap
}

jsfiddle

Upvotes: 1

martincarlin87
martincarlin87

Reputation: 11042

You could adjust the td styles to include white-space: nowrap;

td {
  border: 1px solid black;
  padding: 5px;
  white-space: nowrap;
}

Also, a couple of your td elements had malformed closing tags.

http://jsfiddle.net/zvmcyp4w/2/

Upvotes: 1

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

Add white-space: pre to the table cells:

td {
    border: 1px solid black;
    padding: 5px;
    white-space: pre;
}

Updated Fiddle.

Upvotes: 1

Related Questions