如何让position:absolute的table填充容器并遵守inset属性?
问题:绝对定位Table如何填充容器并遵守inset边距设置?
我在div容器内放置了一个table,给table设置了position: absolute和inset: 50px,但当前table并未填满div扣除inset后的可用空间,想实现table宽高填充容器同时保留inset边距的效果。
当前代码
HTML
<div> <table> <tr> <td> <label>hello</label> </td> <td> <label>hello</label> </td> </tr> <tr> <td> <label>hello</label> </td> <td> <label>hello</label> </td> </tr> </table> </div>
CSS
table { position: absolute; inset: 50px; background-color: green; border-collapse: collapse; } div { width: 400px; height: 400px; background-color: yellow; } label { background: red; } table, th, td { border: 1px solid black; }
效果对比
当前显示效果

预期显示效果

解决方案
1. 修正父级定位参考
首先给div添加position: relative,确保table的绝对定位是相对于div(而非页面视口)生效:
div { width: 400px; height: 400px; background-color: yellow; position: relative; /* 新增 */ }
2. 强制table拉伸填充空间
table默认是自适应内容的布局,即使设置了绝对定位和inset也不会自动拉伸。添加table-layout: fixed启用固定布局,让table自动填满inset限定的区域:
table { position: absolute; inset: 50px; background-color: green; border-collapse: collapse; table-layout: fixed; /* 新增 */ }
这样修改后,table就会填满div中扣除上下左右50px边距后的区域,完全符合预期效果。
内容的提问来源于stack exchange,提问作者Chin
相关产品推荐
相关产品推荐

