Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 744
Matthew Avatar asked Apr 23 '10 16:04

Matthew


2 Answers

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>
like image 64
Markus Avatar answered Oct 13 '22 21:10

Markus


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

like image 39
BalusC Avatar answered Oct 13 '22 20:10

BalusC