【问题标题】:Max-height of table-cell表格单元格的最大高度
【发布时间】:2015-08-13 04:51:23
【问题描述】:

如何设置表格单元格的高度?将display:blockoverflow: hidden 设置为#table 并不是一个好的解决方案。 #table-cell1 和 #table-cell2(当然还有整个表格)应该是 30px。如何解决?

如果文本太多,则 div 会调整大小。在这种情况下,#table-cell2 的高度是 100px,即使有这么多的文字,也应该保持固定为 30px!

参见小提琴:http://jsfiddle.net/HPtB2/1

【问题讨论】:

    标签: html css


    【解决方案1】:

    height 属性应用于表格单元格时(无论是使用像<td> 这样的原生标签还是像display: table-cell 这样启用的CSS),它被解释为一个最小值。

    表格单元格的高度将根据需要扩展以容纳内容,而这又会确定包含该单元格的表格行的高度。

    参考:http://www.w3.org/TR/CSS2/tables.html#height-layout

    如何在表格单元格中固定高度

    在表格单元格中设置固定高度的一种方法是对表格单元格的内容使用包装器:

    <div id="table">
        <div id="table-cell1">
            <div class="inner-cell">table cell 1</div>
        </div>
        <div id="table-cell2">
            <div class="inner-cell">table cell 2
                <br/>Table
                <br/>Cell</div>
        </div>
    </div>
    

    并应用以下 CSS:

    body {
        margin: 0
    }
    #table {
        display: table;
        width: 100%;
        height: 30px;
        /* ignored */
    }
    #table-cell1 {
        display: table-cell;
        width: 80px;
        background-color: yellow;
    }
    #table-cell2 {
        display: table-cell;
        background-color: gray;
        color: white;
    }
    .inner-cell {
        border: 1px dashed blue;
        height: 30px;
        overflow: auto; /* optional: if needed */
    }
    

    诀窍是为块级容器.inner-cell 设置一个固定(或最大)高度值。

    如果需要滚动条等,也可以设置overflow属性。

    见演示小提琴:http://jsfiddle.net/audetwebdesign/mNcm5/

    【讨论】:

    • 优秀的解决方案!谢谢!
    • 嗯...你为什么不在这里使用一张桌子?
    【解决方案2】:

    从您的 html 中删除 &lt;br&gt;

    <div id="table-cell2">table cell 2  Table  Cell</div>
    

    添加:

    div {    
     white-space:nowrap;
        }
    

    【讨论】:

    • 这就是为什么你的文字会下降
    • 如果文本太多,则 div 将调整大小。在这种情况下,#table-cell2 的高度是 100px,即使有这么多的文字,也应该保持固定为 30px! jsfiddle.net/HPtB2/1
    【解决方案3】:

    这就是你所追求的吗?你很模糊

    #table-cell1{
    display: table-cell;
    width: 80px;
    height:200px;
    background-color: yellow;
    }
    

    【讨论】:

    • 谢谢你的替换,但它不起作用,试着把30px而不是200px。
    • 您是否希望所有文本都跨行而不是下拉?
    • 是的,高度不应该缩小!
    【解决方案4】:

    使用 Javascript 限制表格中所有单元格或行的最大高度:

    此脚本适用于水平溢出表。

    此脚本每次将表格宽度增加 300px,最大 4000px) 直到行缩小到 max-height(160px) ,您也可以根据需要编辑数字。

    var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
    while (row = table.rows[i++]) {
        while (row.offsetHeight > 160 && j < 4000) {
            j += 300;
            table.style.width = j + 'px';
        }
    }
    

    来源:HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

    【讨论】:

    • 这个答案没有回答 OP 的问题而且是矫枉过正
    猜你喜欢
    • 2023-03-23
    • 2011-10-26
    • 2012-11-20
    • 1970-01-01
    • 2012-04-09
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多