【问题标题】:Setting column width in HTML table在 HTML 表格中设置列宽
【发布时间】:2011-11-22 08:27:22
【问题描述】:

目前,我有一个看起来像这样的表

<table>
    <tr>
        <th>Submitted</th>
        <th>Title</th>
        <th>Revisions</th>
    </tr>
    <tr>
        <td>Nov. 22, 2011, 2:14 a.m.</td>
        <td><a href="/essays/edit/6">Hello</a></td>
        <td>2</td>
    </tr>
</table>

我需要Title 列尽可能宽,而其他列刚好 可以包含它们的内容。我还需要表格填充其容器(100% 宽度)。
如何实现?

【问题讨论】:

    标签: html css xhtml html-table


    【解决方案1】:

    这可能是一种快速而肮脏的 hack,但您可以简单地使用以下 CSS:

    td, th {
        white-space: nowrap; /* to prevent splitting content into several lines */
    }
    th:nth-of-type(2) {
        width: 100%;
    }
    

    表格内的单元格不可能超过其整体宽度,因此它可以工作。

    您也可以使用 JavaScript 动态计算中间列宽或设置固定单元格宽度。

    【讨论】:

    • 它使其他列太窄并将内容推到下一行。看起来不太好。
    • 你总是可以在 CSS 中设置 "min-width" 或 "white-space: nowrap;"以防止将内容放入下一行。
    • 输入“空白:nowrap;”第一行对其他人无济于事。把它放在每一行都会违反 DRY。我觉得 min-width 也不能很好地工作,因为列宽可能会在浏览器和表格中发生变化。我正在寻找适用于所有表格的通用解决方案。
    • 如果你使用类似的东西,就会违反 DRY: td:nth-of-type(1) { white-space: nowrap; } td:nth-of-type(3) { white-space: nowrap; } 你很挑剔,哈哈。我提到的解决方案对我有用。
    猜你喜欢
    • 2012-08-13
    • 1970-01-01
    • 2010-10-30
    • 2014-11-19
    • 2020-09-15
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多