Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML table scale to fit

I have a KPI dashboard with a lot of small charts. One type of chart is in fact a HTML table. It is displayed in a DIV.

<div style="width:400px; height:250px;overflow:hidden">
   <table>
       <tr><th>Col1</th><th>Col2</th></tr>
       <tr><td>Row1</td><td>Row2</td></tr>
   </table>
<div>

Currently, I hide the overflow. I would like to make the table 'fit' the div.

How can I make this table to fit/scale down to the DIV if it would become too big to diplay? Ideally, the text would also shrink.

like image 493
Rob Audenaerde Avatar asked Nov 03 '14 10:11

Rob Audenaerde


People also ask

How do I fit an HTML table to fit the screen?

To make an HTML table tit the screen: Set the width to 100%, so that your code will look like this: <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>My html table is set to fit the screen</td> </tr> ...

How do you adjust a table in HTML?

To manipulate the height or width of an entire table, place the size attribute (either "WIDTH=" or "HEIGHT=") within the <TABLE> code. To manipulate individual cells, place the size attribute within the code for that cell.

How do I fix TD size in HTML?

By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table.


1 Answers

This CSS will make your table have the same height/width as the container you are using. Borders/background are only added for visualising what happens.

Shrinking the text will however be far more challenging. There is probably no way without using javascript to achieve that. And even if you did, content might end up being unreadable because of a too small font-size.

I managed to come up with some javascript/jquery code to change the font-size until the table fits the div or the font-size reaches 5px (= unreadable). Of coarse you will need to edit some of it yourself (because it would apply on all tables if you don't change the selectors to id's)

[JSFiddle]

table{ 
    width: 100%;
    background-color: red;
}
th, td{
    width: 50%;
    border: blue solid 1px;    
}

Jquery / Javascript

$(document).ready(function () {
    var HeightDiv = $("div").height();
    var HeightTable = $("table").height();
    if (HeightTable > HeightDiv) {
        var FontSizeTable = parseInt($("table").css("font-size"), 10);
        while (HeightTable > HeightDiv && FontSizeTable > 5) {
            FontSizeTable--;
            $("table").css("font-size", FontSizeTable);
            HeightTable = $("table").height();
        }
    }
});
like image 139
Rob Monhemius Avatar answered Oct 24 '22 05:10

Rob Monhemius