如何让Grid布局的grid-template-rows实现行高互相依赖?
Grid布局中grid-template-rows的自定义高度规则实现问题
需求说明
- 若某行无内容,且另一行无内容或内容高度超过50px,则该行高度设为50px;
- 若另一行内容高度小于50px,则该行高度与另一行相同;
- 若该行自身有内容,则高度为内容自身高度。
示例代码
CSS
.grid-container { display: grid; grid-template-rows: auto auto; border: 1px solid gray; margin-bottom: 16px; } .grid-container>div:nth-child(1) { background: lime; } .row1 { height: 50px; } .row2 { height: 100px; } .row3 { height: 30px; } .row4 { height: 30px; } .row5 { height: 25px; } .row6 { height: 40px; } .row7 { height: 50px; } .row8 { height: 50px; }
HTML
<div class="grid-container"> <div class="row1"> I am empty row my height is 50px as other row content is higher than 50px; </div> <div class="row2"> My content height is 100px; </div> </div> <div class="grid-container"> <div class="row3"> I am empty row my height is 30px because other row content is smaller than 50px and is 30px; </div> <div class="row4"> My content height is 30px; </div> </div> <div class="grid-container"> <div class="row5"> I have content of height 25px so I am 25px in height, so other row height doesn't matter; </div> <div class="row6"> I have content of 40px; </div> </div> <div class="grid-container"> <div class="row7"> I am empty and other row empty so we both 50px; </div> <div class="row8"> I am empty and other row empty so we both 50px; </div> </div>
解决方案
仅通过grid-template-rows属性无法完全实现你描述的所有规则——Grid布局的行高度计算逻辑基于自身内容或显式定义的尺寸,无法直接关联另一行的高度状态。不过可以结合Grid属性与额外的CSS规则达成需求:
.grid-container { display: grid; grid-template-rows: auto auto; border: 1px solid gray; margin-bottom: 16px; } .grid-container > div:nth-child(1) { background: lime; } /* 空行默认最小高度50px */ .grid-container > div:empty { min-height: 50px; } /* 当容器内存在非空行时,空行高度取内容行高度与50px的较小值 */ .grid-container:has(> div:not(:empty)) > div:empty { height: min(var(--content-row-height), 50px); } /* 为非空行设置高度变量,供空行引用 */ .grid-container > div:not(:empty) { --content-row-height: auto; } /* 针对示例中的固定高度行,显式绑定变量值 */ .row3, .row4 { --content-row-height: 30px; } .row5 { --content-row-height: 25px; } .row6 { --content-row-height: 40px; }
如果需要兼容不支持:has()选择器的浏览器,也可以通过为不同场景的容器添加类名(比如has-short-content),再针对性设置空行高度。
内容的提问来源于stack exchange,提问作者Andyally
相关产品推荐
相关产品推荐

