【问题标题】:Table cell td with max-width showing too much white space if line breaks如果换行符,具有最大宽度的表格单元格 td 显示过多的空白
【发布时间】:2013-12-23 03:18:51
【问题描述】:

我正在尝试使一张桌子尽可能小。一个单元格的内容可能比所需的宽度多,所以我设置了“最大宽度”。所以在某些情况下,内容会被分成更多的行,这很好。 但是,当一个换行符分成两部分时,表格单元格保持在最大宽度,而如果它可以调整到现在中断的内容,它可能会更小。

字多,容易看:http://jsfiddle.net/G3bcB/10/

<p>Too much white space:</p>
<table>
    <tr>
        <td class="leftcell">long texttext overflow</td>
        <td>B</td>
        <td>C</td>
    </tr>
</table>
<p>Upper table could have same width:</p>
<table>
    <tr>
        <td class="leftcell">long texttext</td>
        <td>B</td>
        <td>C</td>
    </tr>
</table>

table  { width: auto;  }
td { border: 1px solid black; }
td.leftcell { max-width: 100px; }

我不确定这是否是 HTML 的一个特性,但对我来说似乎是错误的。

是否可以使字段更小(使用标准 css)?

【问题讨论】:

  • 是否需要显示所有文本?将它放入 td 的唯一方法是 (1) 通过裁剪、字体大小等使其更小,以及 (2) 在 td 中放置一个 div 并溢出:隐藏、空白:nowrap 等。
  • 同样的问题出现在 FF、IE 和 Chrome 中。如果您在其中粘贴
    ,则 td 将最小化。我同意这似乎是错误的。

标签: css html-table


【解决方案1】:

如果没有 Javascript,您将无法做到这一点。幸运的是,它并不太复杂。我将第一个单元格的类更改为 leftcell1 以将其与下部表格区分开来,并为演示目的延长了字符串:

<td class="leftcell1">
    long texttext overflow long overflow
</td>

这是更新后的jsFiddle

还有 javascript:

var el = $('.leftcell1');

//temporarily puts the text in the cell to measure it
function getWidth(el, txt) {
    el.html(txt);
    return el.css('width').replace('px', '');
}

//returns the string w/ the <br /> tags in the right place
function splitString(maxWidth) {
    var txtArr;
    var presentTxt = '';
    var futureTxt = '';
    var finalTxt = '';
    //split the words up if longer than the max width
    if (getWidth(el, el.html()) >= maxWidth) {
        txtArr = el.html().split(' ');
        //loop through the words and add them together
        for (var i in txtArr) {
            futureTxt += txtArr[i] + ' ';
            //check if the string is longer than the max width
            if (getWidth(el, futureTxt) > maxWidth) {
                //It is. Add it to the final string with a <br /> 
                //and chop off the trailing space
                finalTxt += presentTxt.substring(0, presentTxt.length - 1) + '<br />';
                futureTxt = presentTxt = txtArr[i] + ' ';
            } else {
                //it's not. Keep adding to it. 
                presentTxt = futureTxt;
            }
        }
    } else {
        finalTxt = el.html();
    }
    //if there is anything leftover in futureTxt add it to finalTxt
    if (futureTxt != '') {
        finalTxt += futureTxt;
    }
    return finalTxt;
}
el.html(splitString(100));

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多