【问题标题】:max-width for cell in wide table宽表中单元格的最大宽度
【发布时间】:2015-08-11 15:59:59
【问题描述】:

我有一张很宽的桌子。由于大多数列具有white-space: nowrap,因此比屏幕宽度宽得多。

我有几个带有white-space: normal 的“包装”列。这些柱子被压得很窄。设置width: 500px 无效。设置min-width: 500px 强制列为500px。

问题是我希望“包装”列占用 0 到 500 像素,具体取决于列的内容。我希望“包装”列不超过 500 像素,但我希望该列占用 500 像素以最小化包装。换句话说,“环绕”列应该扩大到 500px,然后开始环绕。

这个jsfiddle 链接显示了问题。如果链接不起作用,只需将以下代码粘贴到 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 解决方案就可以了。

【问题讨论】:

  • 你需要 JavaScript/jQuery 来实现这个布局。 CSS 表格布局算法将尝试最小化表格的整体宽度,在这种情况下,它通过强制第一列换行来实现这一点。没有 CSS 属性或函数可以指示“将内容扩展到一定长度然后开始换行”。

标签: html css width max html-table


【解决方案1】:

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

您需要将您的内容包装在div 的第一列中。诀窍是最初强制div 使用非换行文本进行扩展。如果结果宽度大于 500 像素,则将宽度设置为 div 并使用普通空白。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 2015-07-29
    • 2023-03-23
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多