text-overflow:没有宽度的表格单元格中的省略号

kra*_*er1 37 html css

我正在尝试text-overflow: ellipsis;在中间单元格中实现响应表宽度,如下所示:

| Button 1 | A one-lined text that is too long and has to be... | Button 2 |

整个表必须width: 100%;与设备一样大.我不能设置固定的宽度上Button 1也没有Button 2因为应用程序是多语种(一个max-width应该是可能的,虽然).

我可以尝试任何我想要的,...只有当我设置固定宽度时才出现.如何在没有JavaScript帮助的情况下告诉中间单元"使用可用空间"?

Fab*_*tté 77

这不是一个干净的解决方案,但它不使用JS,并且可以在我测试过的每个浏览器中使用.

我的解决方案是将单元格的内容用table-layout: fixed和包装在表格中width: 100%.

演示.

这是完整的解决方案:

<table class="main-table">
    <tr>
        <td class="nowrap">Button 1</td>
        <td>
            <table class="fixed-table">
                <tr>
                    <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus doloremque magni illo reprehenderit consequuntur quia dicta labore veniam distinctio quod iure vitae porro nesciunt. Minus ipsam facilis! Velit sapiente numquam.</td>
                </tr>
            </table>
        </td>
        <td class="nowrap">Button 2</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

.main-table {
    width: 100%;
}

.fixed-table {
    /* magic */
    width: 100%;
    table-layout: fixed;

    /*not really necessary, removes extra white space */
    border-collapse: collapse;
    border-spacing: 0;
    border: 0;
}
.fixed-table td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.nowrap {
    /* used to keep buttons' text in a single line,
     * remove this class to allow natural line-breaking.
     */
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)

目前还不清楚侧按钮的意图是什么,因此我习惯white-space: nowrap将它们保持在同一条线上.根据用例的不同,您可能更愿意应用a min-width并让它们自然换行.

  • Heheh不用担心,我希望看到一个更清晰的答案,所以让我们拭目以待吧.我实际上在生产环境中有这个答案的代码,它感觉不是很干净,但是,我已经挣扎了几天,这是唯一能在每个浏览器中实际运行的解决方案. (2认同)

pet*_*ete 18

在表格上设置100%宽度并指定fixed表格布局:

table {
    width: 100%;
    table-layout: fixed;
}
Run Code Online (Sandbox Code Playgroud)

然后,为具有省略号的表格单元格设置以下内容:

td:nth-child(2) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)

瞧!带有省略号溢出的响应表!

演示:http://jsfiddle.net/VyxES/

  • 这是一个很好的解决方案,应用“table-layout:fixed”的唯一缺点是它平均分割单元格的宽度(除非手动设置)而不是基于内容。 (2认同)
  • 同意,很大的缺点,OP希望第1和第3单元格只有它们的内容宽,并且中心单元格占据剩余的宽度. (2认同)

小智 8

HTML

<tr>
    <td>
        <span class="ellipsis"> A very looooooooooooooooooooooooooooooong string</span>
    </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

CSS

td {
    position: relative;
}

.ellipsis {
    /*Here is the trick:*/
    position: absolute;
    width: 100%;
    /*End of the trick*/

    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)


Twe*_*eZz -1

[更新]我很抱歉,似乎不能“像那样”工作: http: //jsfiddle.net/kQKfc/1/

不过还是把它留在这里,因为在某些情况下它对我们有用。
[/更新]

我们的项目中有这个 css,试一下:

.nowr
{
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)