宽 table 中单元格的最大宽度

max-width for cell in wide table

我有一个 table 很宽。由于大多数列具有 white-space: nowrap.

,因此比屏幕宽度宽得多

我有几个 "wrapping" 列 white-space: normal。这些柱子被压得很窄。设置 width: 500px 无效。设置 min-width: 500px 强制列为 500px。

问题是我希望 "wrapping" 列根据列的内容采用 0 到 500 像素。我希望 "wrapping" 列不超过 500px,但我希望该列采用 500px 以最小化换行。换句话说,"wrapping" 列应该扩展到 500px,然后开始换行。

jsfiddle link 显示了问题。如果 link 不起作用,只需将以下代码粘贴到 jsfiddle.net.

<html>
    <body>
        <table border="1">
            <tr>
                <td style="max-width: 500px;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
                <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
                <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
                <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
            </tr>
        </table>
    </body>
</html>

编辑: JavaScript 解决方案就可以了。

这是一种使用 jQuery 确定何时开始换行的方法。唯一的硬编码参数是最大宽度 500px。

您需要将您的内容放在 div 的第一列中。诀窍是最初强制 div 使用非换行文本展开。如果生成的宽度大于 500px,则将宽度设置为 div 并使用普通白色-space.

var $div_w = $(".col1 div").width();

if ($div_w > 500) {
    $(".col1 div").addClass("wrapit");
}
.col1 {
    width: auto;
}
.col1 div {
    white-space: nowrap;
    border: 1px dashed blue;
}
.col1 div.wrapit {
    width: 500px;
    white-space: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
    <tr>
        <td class="col1"><div>Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</div></td>
        <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
        <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
        <td style="white-space: nowrap;">Hello World!  This is a very wide cell.  I hope it will wrap.  I am trying to make it very wide.  I might need some more text.</td>
    </tr>
</table>