html - 宽表中单元格的最大宽度

标签 html css width max html-table

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

我有一些带有 white-space: normal 的“环绕”列。这些柱子被压得很窄。设置 width: 500px 没有效果。设置 min-width: 500px 强制列为 500px。

问题是我希望“环绕”列根据列的内容采用 0 到 500 像素。我希望“环绕”列不超过 500 像素,但我希望该列采用 500 像素以最小化环绕。换句话说,“wrapping”列应该扩展到 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 解决方案就可以了。

最佳答案

这是一种使用 jQuery 来确定何时开始环绕文本的方法。唯一的硬编码参数是最大宽度 500 像素。

您需要将您的内容包装在 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>

关于html - 宽表中单元格的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30518508/

相关文章:

javascript - 带有CSS转换的 slider 中的无限循环

css - 无法加载 Bootstrap.css 库

css - webkit 只是切断了 css 编号中的小数点……如何解决?

css - Textarea max-width 没有得到尊重

HTML 表 : THEAD width depending on TBODY in Chrome

php - 复制一个单词并将其保存为一个变量

javascript - 如何使用 Javascript 滚动到下一个 div?

javascript - 循环遍历数组并使用 d3 将每个项目分配为 html 标签中的类

javascript - 删除继承的 CSS 值?

css - @ font-face可以在IE8中加载,但随后翻转为后备字体;还大胆?