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?
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).
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>
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"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With