宽表中单元格的最大宽度

时间:2015-05-28 23:06:35

标签: html css width max html-table

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

我有一些"包装" white-space: normal的列。这些柱子被压得非常狭窄。设置width: 500px无效。设置min-width: 500px会强制列为500px。

问题是我想要"包装"列取0到500px,具体取决于列的内容。我想要"包装"列不要超过500px但我希望列采用500px来最小化包装。换句话说,"包装"列应扩展到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解决方案没问题。

1 个答案:

答案 0 :(得分:1)

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

您需要将内容包装在div的第一列中。诀窍是最初强制div扩展非包装文本。如果生成的宽度大于500px,则将宽度设置为div并使用正常的空格。

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

if ($div_w > 500) {
    $(".col1 div").addClass("wrapit");
}
&#13;
.col1 {
    width: auto;
}
.col1 div {
    white-space: nowrap;
    border: 1px dashed blue;
}
.col1 div.wrapit {
    width: 500px;
    white-space: normal;
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题