如何让未设置高度的子div与父div高度一致?
解决子div
height:100% 不生效的问题 问题原因
当给元素设置height:100%时,浏览器要求它的父元素必须有显式指定的高度值(比如height: 300px、height: 50vh)才能生效。如果父元素的高度是由内部子元素撑开的(即自适应高度),height:100%会因为没有明确的参考高度而失效。
解决方案
方案1:使用Flexbox布局(推荐)
给父div设置display: flex,子元素会默认拉伸至父元素高度,无需额外设置height:100%:
.parent { display: flex; border: 1px solid red; /* 若需要子元素换行,可添加flex-wrap: wrap */ } .child-1 { height: 200px; width: 100px; border: 1px solid blue; } .child-2 { width: 100px; border: 1px solid green; }
方案2:使用Grid布局
给父div设置display: grid并指定列布局,子元素自动匹配父元素高度:
.parent { display: grid; grid-template-columns: auto auto; border: 1px solid red; } .child-1 { height: 200px; width: 100px; border: 1px solid blue; } .child-2 { width: 100px; border: 1px solid green; }
方案3:给父元素设置显式高度(固定高度场景适用)
如果父元素高度可确定,直接给父div设置固定高度,此时height:100%即可生效:
.parent { height: 200px; border: 1px solid red; } .child-1 { height: 200px; width: 100px; border: 1px solid blue; } .child-2 { height: 100%; width: 100px; border: 1px solid green; }
方案4:使用绝对定位
给父div设置position: relative,child-2设置绝对定位并拉伸至父元素高度:
.parent { position: relative; border: 1px solid red; overflow: auto; /* 避免内容溢出 */ } .child-1 { height: 200px; width: 100px; border: 1px solid blue; margin-right: 100px; /* 避免与绝对定位元素重叠 */ } .child-2 { position: absolute; top: 0; bottom: 0; left: 100px; /* 与child-1宽度对齐 */ width: 100px; border: 1px solid green; }
内容的提问来源于stack exchange,提问作者user19348133
相关产品推荐
相关产品推荐

