Matthew
Matthew

Reputation: 15642

Table column width as narrow as contained data?

I have three columns. The last two I want to make as narrow as the their contained data and the first column can take the rest of the width (table has 100% width).

How can you do this using CSS? Right now the columns on the right look silly with extra space. Ideas?

Upvotes: 12

Views: 13686

Answers (2)

Markus
Markus

Reputation: 5807

I just answered this with a little different approach with this more detailsed answer in a similar question, basically:

Add the class shrink to columns you want to have as narrow as possible

<table>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
</table>

With this css:

td.shrink {
  white-space: nowrap;
  width: 1px;
}

With this you can define multiple columns to have minimum width on one line but the other's width stays dynamic (including possible line breaks).

Example Snippet

table {
  width: 100%;
}

td {
  padding: 10px;
}

td.shrink {
  white-space: nowrap;
  width: 1px;
}
<table>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
    <tr><td>first</td><td class="shrink">second</td><td class="shrink">third</td></tr>
</table>

Upvotes: 3

BalusC
BalusC

Reputation: 1108712

Just give the first column a width of 100% and if necessary give the cells in all other columns a white-space: nowrap to avoid their content being wrapped (again, only if necessary).

E.g.

<table>
    <tr><td class="first">first</td><td>second</td><td>third</td></tr>
    <tr><td class="first">first</td><td>second</td><td>third</td></tr>
    <tr><td class="first">first</td><td>second</td><td>third</td></tr>
</table>

with

table { width: 100%; }
table td.first { width: 100%; }

Or the modern way if you don't bother about IE6 users:

table { width: 100%; }
table td:first-child { width: 100%; } 

(so that you can remove class="first")

Upvotes: 16

Related Questions