垂直调整浏览器大小时如何避免网页内容出现重叠问题
问题原因
重叠问题确实是大量使用position: absolute导致的:所有元素都相对于视口固定位置,不参与正常文档流排版,当视口高度变小时,固定位置的元素自然会互相挤压重叠。
修复步骤
- 第一步:在
<head>标签最顶部添加移动端适配必备的viewport元标签,避免移动端自动缩放页面
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- 第二步:修改body样式,用flex布局实现整体内容的居中排版,替代绝对定位
body { background-color: black; color: white; font-family: Arial, Helvetica, sans-serif; /* 替换原来的display:block */ display: flex; flex-direction: column; align-items: center; min-height: 100vh; margin: 0; padding: 20px 0; /* 上下留边避免内容贴边 */ box-sizing: border-box; }
- 第三步:删除
.centered和.lower-center里所有绝对定位相关的属性,只保留需要的文字样式,加合适的间距即可
.centered { /* 原有的position、top、left、margin-right、transform属性全部删除 */ margin-bottom: 16px; /* 可自行调整和下方介绍文本的间距 */ } .logosize { font-size: 2em; letter-spacing: -5px; } .lower-center { /* 原有的position、top、left、margin-right、transform属性全部删除 */ line-height: 18px; text-align: center; }
- 第四步:修改footer的样式,删掉绝对定位,用flex的自动margin实现底部停靠,不会压到上层内容
footer { text-decoration: none; font-size: 1em; /* 原有的position、bottom、width属性全部删除 */ height: 4rem; display: flex; justify-content: center; margin-top: auto; /* 自动靠到页面最底部 */ }
修复后完整代码
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .logo { color: white; font-size: 2em; font-weight: bolder; margin: 0; } a:link { color: white; } a:visited { color: white; } body { background-color: black; color: white; font-family: Arial, Helvetica, sans-serif; display: flex; flex-direction: column; align-items: center; min-height: 100vh; margin: 0; padding: 20px 0; box-sizing: border-box; } .centered { margin-bottom: 16px; } .logosize { font-size: 2em; letter-spacing: -5px; } .lower-center { line-height: 18px; text-align: center; } .location-text { font-size: 15px; } footer { text-decoration: none; font-size: 1em; height: 4rem; display: flex; justify-content: center; margin-top: auto; } .footer ol { display: flex; list-style: none; padding: 0; margin: 0; } .footer ol li {margin: 1em;} .footer ol li a{ text-decoration: none; } .footer ol li a:hover {color: rgb(83, 54, 150);} </style> </head> <body> <div class="centered logosize"> <p class="logo" id="typewriter">daniel m.</p> </div> <div class="lower-center location-text"> <p><span style='font-size:13px;'>📍</span> las vegas <br>web developer _ creator</p> </div> </body> <footer class="footer"> <ol> <li><a href="https://instagram.com/_ddmm"><img class="instagram-icon" src="images/instagram-icon.png" alt="instagram"></a></li> <li><a href="https://twitter.com/_DDMM"><img class="twitter-icon" src="images/twitter-icon.png" alt="twitter"></a></li> <li><a href="https://github.com/dannymaclaughlin"><img class="github-icon" src="images/github-icon.png" alt="github"></a></li> </ol> </footer> </html>
内容的提问来源于stack exchange,提问作者Daniel M.
相关产品推荐
相关产品推荐

