HTML元素无法占满屏幕100%高度,求修复方案
问题:如何让元素占满屏幕100%高度?
我希望目标元素能占满屏幕100%高度,但当前并未实现。我观察到div的高度为section的100%,section的高度为body的100%,且body已设置为100%高度。
原HTML代码
<body> <section id="Block1"> <div class="firstsection"> <h1>Lorem Ipsum</h1> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nemo magnam iusto quibusdam quas reiciendis fugit architecto consequatur similique distinctio dolore repudiandae rem illo alias iure sunt eos culpa, amet consectetur!</p> </div> </section> </body>
原CSS代码
body { width: 100%; height: 100%; } * { padding: 0px; margin: 0px; } .firstsection { width: 50%; height: 100%; background-color: yellowgreen; text-align: center; } #Block1 { width: 100%; height: 100%; }
修复方法
问题核心是html元素未设置高度:CSS中百分比高度是基于父元素的,body的父元素是html,默认情况下html没有明确高度值,导致body的height:100%无法生效,后续子元素的百分比高度自然也无法占满屏幕。
方法1:为html元素添加100%高度
给html设置height:100%,让body的百分比高度有参考基准:
html, body { width: 100%; height: 100%; } * { padding: 0; margin: 0; } .firstsection { width: 50%; height: 100%; background-color: yellowgreen; text-align: center; } #Block1 { width: 100%; height: 100%; }
方法2:使用视口单位vh(更推荐)
100vh表示直接占满当前视口的100%高度,无需依赖父元素高度设置,写法更简洁:
* { padding: 0; margin: 0; } #Block1 { width: 100%; height: 100vh; } .firstsection { width: 50%; height: 100%; background-color: yellowgreen; text-align: center; }
内容的提问来源于stack exchange,提问作者EverythingDoesn'tMakeSense
相关产品推荐
相关产品推荐

