RobAu RobAu - 3 months ago 6x
HTML Question

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">

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

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


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)


    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) {
            $("table").css("font-size", FontSizeTable);
            HeightTable = $("table").height();