【问题标题】:CSS word-wrap does not work in table [duplicate]CSS自动换行在表格中不起作用[重复]
【发布时间】:2016-08-29 21:00:44
【问题描述】:

我需要创建一个带有固定标题的表格、一个可在 Y 轴(但不能在 X 轴上)滚动的表格主体和固定宽度的列。

我找到了我的问题的答案:https://stackoverflow.com/a/17585032/6033166

它就像一个魅力(非常感谢!),我开始根据这个答案编写我的代码。我添加了table-layout: fixedword-wrap: break-wordoverflow-y: auto; overflow-x: hidden; 以满足我的额外需求。

但是还有一个问题。如果在表格单元格中输入了很长的文本,没有(或只有很少)空格,则不会添加换行符,而是会通过蛮力改变宽度,表格行为该行“腾出空间”大入口,将其他单元推到两侧。

我找到了关于 SO 的答案和建议,其中说我可以将 <wbr> 标记添加到内容中,从而建议浏览器何时进行换行。这里的问题是内容是从数据库中检索的(通过 C#),然后需要在显示之前进行处理,如果可能的话,我想跳过这个步骤。如果有什么办法,我想把它保存在 CSS 中。但是,如果没有其他可能性,我也非常愿意接受其他解决方案。
我也试过了,同样的结果。

这是我当前的表格 CSS:

    table.tableSection {
    display: table;
    width: 100%;
    table-layout: fixed;
    word-wrap: break-word;
}
table.tableSection thead, table.tableSection tbody {
    float: left;
    width: 100%;
}
table.tableSection tbody {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100px;
}
table.tableSection tr {
    width: 100%;
    display: table;
    text-align: left;
}
table.tableSection th, table.tableSection td {
    width: 33%;
}

这是 HTML 代码:

<table class="tableSection">
<thead>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Text</td>
        <td>Text</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>This does work very well with blank spaces. The text has no limitation in size, line breaks will simply be added.</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>This_does_not_work_sadly,_which_is_a_huge_problem,_since_blank_spaces_are_not_permitted_as_word_delimiters.</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>Text</td>
        <td>Text</td>
    </tr>
</tbody>

这是一个指向我的 jsfiddle 的链接来说明我的意思:https://jsfiddle.net/Fi_Vi/bmc7r8rz/3/

【问题讨论】:

    标签: html css word-wrap


    【解决方案1】:

    我会使用简单的:

    table.tableSection th, table.tableSection td {
      float: left;
      width: 33%;
      word-wrap: break-all;
    }
    

    【讨论】:

      【解决方案2】:

      将以下代码添加到您的 td 的 CSS 样式 table.tableSection th, table.tableSection td { ... }

      word-break: break-all;
      

      这是更新后的小提琴: https://jsfiddle.net/bmc7r8rz/8/

      【讨论】:

      • 谢谢,完美运行!我的错误是'word-break:break-all;'是我把它放到'table.tableSection'中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2015-01-21
      • 1970-01-01
      • 2017-09-21
      • 2012-12-05
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多