表格单元格td,如果换行,最大宽度显示太多的空白区域

时间:2013-12-21 21:34:22

标签: css html-table

我想尽可能地制作一张桌子。一个单元格可能具有更多的内容,然后是所需的宽度,因此我设置“max-width”。因此在某些情况下,内容将被分解为更多行,这很好。 但是,当一行中断时,表格单元格保持最大宽度,而如果它会调整为现在已损坏的内容,则可能会更小。

很多单词,易于查看: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)?

1 个答案:

答案 0 :(得分:0)

如果没有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));