HTML 表格比例适合

问题描述 投票:0回答:3

我有一个 KPI 仪表板,其中有很多小图表。一种类型的图表实际上是 HTML 表格。它显示在 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>

目前,我隐藏了溢出。我想让表格“适合”div。

如果

table
变得太大而无法显示,我该如何使其适合/缩小到
DIV
?理想情况下,文本也会缩小。

html css html-table width scaling
3个回答
5
投票

此 CSS 将使您的表格与您正在使用的容器具有相同的高度/宽度。添加边框/背景只是为了可视化发生的情况。

然而,缩小文本将更具挑战性。如果不使用 javascript 可能就没有办法实现这一点。即使您这样做了,内容也可能会因为字体太小而无法阅读。

我设法想出了一些 javascript/jquery 代码来更改字体大小,直到表格适合 div 或字体大小达到 5px(= 不可读)。粗略地说,您需要自己编辑其中一些内容(因为如果您不将选择器更改为 id,它将应用于所有表)

[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();
        }
    }
});

0
投票

这是我目前使用的,它嵌入到项目中(例如,参见类),但请随意使用它作为灵感。

scaleTable = function (markupId) {

                //This hacky stuff is used because the table is invisible in IE.  
                function realWidth(obj){
                    var clone = obj.clone();
                    clone.css("visibility","hidden");
                    $('body').append(clone);
                    var width = clone.outerWidth();
                    clone.remove();
                    return width;
                }
                function realHeight(obj){
                    var clone = obj.clone();
                    clone.css("visibility","hidden");
                    $('body').append(clone);
                    var height = clone.outerHeight();
                    clone.remove();
                    return height;
                }

                var table = $("#"+markupId+" table:first-of-type");

                var tablecontainer = $("#"+markupId).parents( ".scalabletablecontainer" );
                var scalex = tablecontainer.innerWidth() / realWidth(table);
                var scaley =  tablecontainer.innerHeight() / realHeight(table);

                var scale = Math.min(scalex, scaley);

                if (scale<1.0) {
                    var fontsize = 12.0 * scale;
                    var padding  = 5.0 * scale;
                    $("#"+markupId+" table tbody").css("font-size", fontsize + "px");
                    $("#"+markupId+" table tbody TD").css("padding",padding + "px");
                    $("#"+markupId+" table TH").css("padding",padding + "px");
                }
            };

0
投票

获取表格和 div 尺寸,如前面的评论所示。然后应用CSS:

transform:scale(factorX, factorY)

到桌子上。

© www.soinside.com 2019 - 2024. All rights reserved.