如何让Grid表格容器适配可见内容?解决高度设置后不收缩问题
问题:Grid表格设置表体溢出后容器无法收缩
我用Grid实现了一个带红色边框的表格,包含表头和绿色边框的表体:
当为表体设置高度并裁剪溢出内容后,表格容器不会收缩:
该如何解决?
原始代码
CSS
* { box-sizing: border-box; } .table { display: grid; grid-template-columns: repeat(2, auto); border: red solid; } .header, .body, .row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; } .body { max-height: 35px; overflow-y: scroll; border: green solid; }
HTML
<!DOCTYPE html> <html lang="en"> <title>Test</title> <body> <div class="table"> <div class="header"> <div class="row"> <div class="cell">Key</div> <div class="cell">Value</div> </div> </div> <div class="body"> <div class="row"> <div class="cell">a</div> <div class="cell">1</div> </div> <div class="row"> <div class="cell">b</div> <div class="cell">2</div> </div> <div class="row"> <div class="cell">c</div> <div class="cell">3</div> </div> <div class="row"> <div class="cell">d</div> <div class="cell">4</div> </div> </div> </div> </body> </html>
解决方案
问题根源是Grid容器会默认参考子元素的原始内容高度(即使子元素设置了overflow),导致容器不会跟随表体的裁剪高度收缩。只需给.table添加grid-template-rows: auto min-content;,让表体所在行的高度按其实际显示的高度计算,而非原始内容高度。
修改后的CSS代码:
* { box-sizing: border-box; } .table { display: grid; grid-template-columns: repeat(2, auto); grid-template-rows: auto min-content; /* 添加这行 */ border: red solid; } .header, .body, .row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; } .body { max-height: 35px; overflow-y: scroll; border: green solid; }
这样设置后,红色边框的表格容器就会自动收缩到表头加上表体的实际显示高度,不会再保留原始内容的高度空间。
内容的提问来源于stack exchange,提问作者Géry Ogam
相关产品推荐
相关产品推荐

