display 属性为 table-row 的元素中调整子元素的高度占比

发布时间 2023-10-27 04:28:25作者: Yukkurii

初始状态效果和代码大致意思如下,业务上需要让TEST1占满td的全部高度

原始 期望
image image
<tr style="display: table-row; background-color: lightgray;">
    <td style="display: table-cell; width: 50px;">
        <div id="TEST1" style="border: 1px solid black; width: 50px;">
            TEST1
        </div>
    </td>
    <td style="display: table-cell;">
        <div>TEST2</div>
        <div>TEST3</div>
    </td>
</tr>

由于td的高度需要根据最高的表格元素自适应,不能写入一个固定高度,而这样height:100%就不能生效。


解决方法1:父相子绝以后用top、bottom设置TEST1高度

<tr style="display: table-row; background-color: lightgray;">
    <td style="display: table-cell; width: 50px; position: relative;">
        <div id="TEST1" style="border: 1px solid black; width: 50px; height:100%; position: absolute; top: 0; bottom: 0;">
            TEST1
        </div>
    </td>
    <td style="display: table-cell;">
        <div>TEST2</div>
        <div>TEST3</div>
    </td>
</tr>

解决方法2:tr的style改为display: table; 然后设置height: 1px;(感觉保不准某个版本浏览器就不支持了)

<tr style="display: table; background-color: lightgray; height: 1px;">
    <td style="display: table-cell; width: 50px; height: 100%;">
        <div id="TEST1" style="border: 1px solid black; width: 50px; height:100%;">
            TEST1
        </div>
    </td>
    <td style="display: table-cell;">
        <div>TEST2</div>
        <div>TEST3</div>
    </td>
</tr>