【问题标题】:Setting a table column's width to max out at the content width of rows below it将表格列的宽度设置为其下方行的内容宽度最大
【发布时间】:2014-08-26 00:44:21
【问题描述】:

我正在使用谷歌浏览器来呈现这个 HTML 页面:

<html>
<style>
    table {
        width: 100%;
    }
    table, td, th {
        border: 1px solid black;
        text-align: left;
    }
    td {
        vertical-align: top;
    }
</style>
<body>
    <table>
        <tr>
            <th>Name</th>
            <th>Value</th>
        </tr>
        <tr>
            <td>Bobby</td>
            <td>100</td>
        </tr>
    </table>
</body>
</html>

上面的代码工作正常。问题是,我希望第一列的宽度不会超过该列中托管的任何行中最长内容宽度的宽度。例如,当我调整窗口大小时,我得到这个:

*---------------------------*---------------------------*
|Name                       |Value                      |
*---------------------------*---------------------------*
|Bobby                      |100                        |
*---------------------------*---------------------------*

但我希望它是这样的:

*-----*-------------------------------------------------*
|Name |Value                                            |
*-----*-------------------------------------------------*
|Bobby|100                                              |
*-----*-------------------------------------------------*

如何做到这一点?

PS:我仍然想保留整个表格占据窗口 100% 宽度的方式。

【问题讨论】:

标签: html css google-chrome resize html-table


【解决方案1】:

只需将:first-child的宽度设置为1px,它应该会根据内容更新宽度。

table th:first-child,
table td:first-child {
    width: 1px;
}

http://jsfiddle.net/sbeliv01/ehpvrzk0/

【讨论】:

    【解决方案2】:

    可以尝试修改基于百分比的宽度以符合表格的宽度

        tr th, 
        tr td {
            width: 90%;
            /* adjust this if the "label" column needs to be longer */
        }
        tr th:first-child,    
        tr td:first-child {
            width: auto;
        }
    

    http://jsfiddle.net/25pjqva4/

    【讨论】:

      【解决方案3】:

      只需将width:auto 属性添加到您的第一个子列。

      table tr td:first-child {
          width:auto;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-25
        • 2020-04-29
        • 2019-01-11
        • 1970-01-01
        • 2019-12-09
        • 2017-02-25
        • 2019-07-22
        • 2011-11-08
        相关资源
        最近更新 更多