开发者

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?


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


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜