将表格列设为与其内容

时间:2017-05-23 09:58:51

标签: html css

我通常使用"宽度:1px"使表格列适应其内容。感觉有点hacky。有更优雅的方式吗?

以下是一个例子:



td {
  background: orange;
}

tr:nth-child(1n+2) td:first-of-type {
  width: 1px;
}

<table>
  <tr>
    <td colspan=2>This is a long text that makes the table wide.<br> The left column should be as small as possible.</td>
  </tr>
  <tr>
    <td>Name</td>
    <td>Joe</td>
  </tr>
  <tr>
    <td>Age </td>
    <td>30</td>
  </tr>
  <tr>
    <td>City</td>
    <td>New York</td>
  </tr>
</table>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这可能是另一种方法。它可能看起来有点不那么“hacky&#39;因为它告诉第二个td占用尽可能多的空间。

&#13;
&#13;
td, th
{
  background: orange;
}



tr:nth-child(1n+2) td:first-of-type
{
 white-space: nowrap;
}

tr:nth-child(1n) td:last-of-type
{
 width: 100%;
}
&#13;
<table>
<tr><td colspan=2>This is a long text that makes the table wide.<br>
                  The left column should be as small as possible.</td></tr>
<tr><td>Name test</td><td>Joe</td></tr>
<tr><td>Age </td><td>30</td></tr>
<tr><td>City</td><td>New York</td></tr>
</table>
&#13;
&#13;
&#13;