简体   繁体   中英

Dynamic width of Table as per column

I have one table which display data as from Dynamic Content, I want to make table width 100% when there is 6 cols. and table width auto if less the 5 cols.

I tried with CSS but, when there is only two cols, it expand two cols to full width while have table 100% width and looks awkward.

Is there any Javascript, jQuery script available to get this result?

Depending on how you're loading the dynamic content, there might be an easier way, but this function should do what you need:

function setTableWidth(tableId) {
    myTable = document.getElementById('tableId');
    if (myTable.getElementsByTagName('tr')[0].getElementsByTagName('td').length > 5)
        myTable.style.width = '100%';
    else
        myTable.style.width = 'auto';
 }

Note though, that it won't work if any of the cells in the first row have a colspan. It's simply counting the number of columns in the first row and setting the width based on that.

Using jQuery and ensuring you choose the first row in the table body in case the thead has a different layout.

function setTableWidth(tableId) {

    var $tbl = $('#'+tableId);
    var newWidth = $tbl.find('tbody>tr:eq(0)>td').length > 5 ? '100%' : 'auto';
    $tbl.width(newWidth)

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM