In HTML table: How to control the row height of a table?

Simple problem: When the table is wider than the screen (overflow) and contains long text in some cells or <td>

, then the row height will become unnecessary.

Before overflow: Normal and valid. http://jsfiddle.net/mg8869ou/1/

After Overflow: Problem after adding cells Only the right side makes unnecessary height for the entire row as well as the entire table. http://jsfiddle.net/w1dc380w/4/

All my tables have different text lengths in cells, different number of rows and columns. Is there a single solution to control the row height of all tables (overflow)?

I think: using whitespace:nowrap

to remove white space or having each single row cell + force of the long cell of each row and column to be square or nearly square will make the table compact.


Solutions not useful For all rows or columns or tables:

(1) css min-width

to columns or cells (2) css width

to table (3) css whitespace:nowrap

to table.

Since all cells have different amounts of text, tables have different widths, number of cells, rows, and columns. Thus, this CSS leaves a useless white space and cannot make the table as compact as possible.

Is there a way to solve this with or without Javascript, or some better way that I think?

+3


source to share


3 answers


No extra white space for you

In your case, this jquery will check each row and increase the width of the table until all rows are nearly equal in height.



var i = 0,
    j, row, table = document.getElementsByTagName('table')[0];
while (row = table.rows[i++]) {
    j = 1000;
    while (row.offsetHeight > 200 && j < 2500) {
        j += 500;
        table.style.width = j + 'px';
    }
}

      

+1


source


Since JQuery = javascript, I hope this is acceptable to you:

http://jsfiddle.net/w1dc380w/8/

$( "th,td" ).each(function( index ) {
$( this ).wrapInner( "<div class='wrapper'></div>"); 


});

      



CSS

.wrapper {
    width:100px;
    height:100px;
}

      

just, we need divs sometimes ... :)

0


source


You have classified this as javascript

, so I'm going to assume that you can use some scripts here. I tried some CSS solutions myself from Google and SO, but unfortunately many of them were responsive and / or relied on knowledge of fixed width - out of the question.

So, I used a javascript snippet to loop through all the elements <td>

, find which one had the greatest height, and then use half that height to make everyone <td>

look roughly square. Fiddle

var greatestHeight = 0;

$('td').each(function(index){
    if($(this).height() > greatestHeight){
        greatestHeight = $(this).height();
    }
});

$('td').css('min-width', (greatestHeight / 2));

      

This is not ideal and I would recommend that you match this table if you have more than one table per page (i.e. td.firstTable

), otherwise the logic will run between tables.

0


source







All Articles