How can I use ellipses in a fluid width table without making each column the same size?

蹲街弑〆低调 提交于 2019-12-03 13:07:36

It should work if you specify a max-width for td.ellipsis.

The solution I found is to style your cells as follows:

td{
    white-space: nowrap;
}

td.description{
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 1px;    
    width: 100%;
}

The first part will force each column to contract as much as possible and ellipsize any clipped text in any cell. However, they will not contract to 1px, because you can use your table-headers to provide a min width. It also prevents line-wrapping within the table.

The second part ensures that all spare space is taken up by the description column, rather than being spread evenly between all columns.

Finally, if you want to impose a true minimum width on the description column, do so by putting the minimum width on the column header rather than on the column cells, as, the max-width aside, the cells cannot contract to be thinner than the header.

See http://jsfiddle.net/BCZTB/ for an implementation.

My solution is to use jquery to get the max width of the text within the column and assign them to the contents width, except for the ellipsis column which will be the maximum size.

My jsfiddle example can be found here http://jsfiddle.net/qt7eQ/1/

<script type="text/javascript">
$(function() {
    //add a innerParagraph block element to all columns except for the one that has the class ellipsis
    $( "#t3 tr td:not(.ellipsis)" ).wrapInner(function() {
          return "<p class='innerParagraph'></p>";
    });

    //get the first column and assign it the width of the elements in the first column
    $( "#t3 tr th:nth-child(1)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(1) p" ) );
    $( "#t3 tr td:nth-child(1)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(1) p" ) );

    //get the second column and assign it the width of the elements in the second column
    $( "#t3 tr th:nth-child(2)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(2) p" ) );
    $( "#t3 tr td:nth-child(2)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(2) p" ) );

    //get the fourth column and assign it the width of the elements in the forth column
    $( "#t3 tr th:nth-child(4)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(4) p" ) );
    $( "#t3 tr td:nth-child(4)" ).width( getMaxWidthOf( "#t3 tr>td:nth-child(4) p" ) );
});


function getMaxWidthOf(selector){
    var maxWidth = 0;
    //go through each paragraph in the right column and find the widest value.
    $(selector).each(function() {
        if(maxWidth < $(this).width()){
            maxWidth = $(this).width();
        }
    });
    // assign max width to column
    return maxWidth;
}
</script>

<!-- add this style -->
<style type="text/css">
#t3 table {
    table-layout:fixed;
{
.innerParagraph {
    margin:0;
    display:inline-block;
}
</style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!