设置高度后DIV仍重叠求助:300vh为何未生效?
解决CSS布局重叠与高度不生效的问题
我来帮你分析下问题所在,以及对应的解决办法:
问题根源拆解
1. HTML标签结构错误(核心原因)
你的代码里存在多处未正确闭合的标签,比如:
<h1>标签用<h2>来闭合,完全不符合语法规范<div class="content_container">没有对应的</div>,反而错误地写了<div>,导致DOM结构嵌套混乱- 最外层的
.seamless_background、#wind_content等容器都没有正确闭合
这种错误会让浏览器自动修正DOM结构,最终导致#grass_content被错误嵌套在#wind_content内部,自然会出现重叠问题。
2. CSS高度与定位的问题
.seamless_background设置了min-height: auto,这等于没设置高度(默认值就是auto),导致子元素#wind_content的height: 100%无法获取到父元素的高度参考,高度设置完全不生效#wind_content和#grass_content使用了position: relative+top: 15vh,这种偏移会让元素相对于原位置下移,但原位置的空间依然被占用,加上结构错误,进一步加剧了重叠
修正后的完整代码
<!DOCTYPE html> <html> <head> <title>seamless_background_test</title> <style> html,body{ margin:0; padding:0; height: 100%; /* 给根元素设置高度,让子元素的%高度有参考基准 */ } .seamless_background{ min-height: 100vh; /* 至少占满视口高度,替代无效的auto设置 */ width: 100%; background: url(./seamless_background_test2a.jpg) center repeat ; display: flex; flex-direction: column; justify-content: flex-start; /* 改为flex-start,让内容从上到下自然排列 */ align-items: center; } .content_container{ min-height: 300vh; background: orange; width: 75%; margin:auto; } .content h1{ padding:15px; color:rgb(140, 49, 0); display:flex; justify-content: center; align-items: center; } #wind_content{ position:relative; width: 100%; margin:auto; margin-top: 15vh; /* 用margin替代top,避免relative偏移导致的布局混乱 */ background:rgba(255, 255, 255, 1); font-family:Arial; /* 修正属性错误:font-style是设置字体样式,font-family才是指定字体 */ font-size: 1.5em; display:flex; justify-content: center; align-items: center; } #grass_content{ position:relative; width: 100%; margin:auto; margin-top: 15vh; background:rgb(197, 245, 66); font-family:Arial; font-size: 1.5em; display:flex; justify-content: center; align-items: center; } </style> </head> <body> <div class="seamless_background" > <div id="wind_content" > <div class="content_container"> <h1>I am an awesome content :)</h1> <!-- 正确闭合h1标签 --> </div> <!-- 闭合content_container容器 --> </div> <!-- 闭合wind_content容器 --> <div id="grass_content" > <div class="content_container"> <h1>I am an awesome content :)</h1> <!-- 正确闭合h1标签 --> </div> <!-- 闭合content_container容器 --> </div> <!-- 闭合grass_content容器 --> </div> <!-- 闭合seamless_background容器 --> </body> </html>
关键修改说明
- 修复HTML结构:把所有未闭合的标签都正确闭合,确保
#wind_content和#grass_content是同级元素,而非错误的嵌套关系 - 根元素高度设置:给
html, body添加height: 100%,让子元素的百分比高度有可参考的基准 - 调整容器高度:把
.seamless_background的min-height: auto改为min-height: 100vh,确保容器至少占满视口高度 - 替换定位偏移方式:把
top:15vh改为margin-top:15vh,用外边距来实现间距,避免relative定位偏移带来的布局混乱 - 修正CSS属性错误:把
font-style:Arial改为font-family:Arial,纠正属性使用错误
这样修改后,两个容器就会按照预期从上到下依次排列,不会再重叠,.content_container的300vh高度也能正常生效。
内容的提问来源于stack exchange,提问作者Diagathe Josué
相关产品推荐
相关产品推荐

