12

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Matthew
  • 15,282
  • 27
  • 88
  • 123

2 Answers2

15

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")

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

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>
Community
  • 1
  • 1
Markus
  • 5,667
  • 4
  • 48
  • 64