HTML table scale to fit

37,539

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();
        }
    }
});
Share:
37,539
Rob Audenaerde
Author by

Rob Audenaerde

Code wizard. Engineer. "An engineer is somebody that solves problems using technology by really understanding both the problem and the technology" or "An engineer is somebody is someone who solves a problem you didn't know you had in a way you don't understand :)” Big believer in SOLID, DRY and general engineering principles. Like the Dutch tend to say: "Meten is Weten"! Current project: Using ElasticSearch to index millions and millions of interesting charts, maps and other data insights. See https://searchdata.com Previous project: Making a Lucene-based BI tool web-and-seo friendly. Example: https://corona.searchdata.com See for my professional profile: http://www.linkedin.com/in/audenaerde

Updated on June 09, 2020

Comments

  • Rob Audenaerde
    Rob Audenaerde almost 4 years

    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.