如何让元素在所有分辨率下显示一致?Gib元素定位问题求助
问题描述
制作个人兴趣网站时遇到元素显示问题:标记为“gib”的元素在1920×1080分辨率下能正确位于白色容器(id为main)的角落,但切换到其他分辨率时,该元素会偏移到页面左侧,其余元素定位均正常,预期效果是让该元素始终固定在白色容器的角落。尝试过设置margin: auto以及修改position属性,但都没有效果。
附上代码:
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="https://files.catbox.moe/lq9k9g.gif"> </head> <style> body { background: url(https://tombrot.neocities.org/graphics/BGs/cemetery.gif); background-size: cover; letter-spacing: 1.5; } #main { width: 300px; height: 300px; margin: auto; margin-top: 100px; padding: 10px; background-color: aliceblue; box-shadow: 0px 0px 30px 30px aliceblue; } .center { display: block; margin-left: auto; margin-right: auto; width: 25%; } #gib { width: 200px; margin: auto; margin-top: -150px; margin-left: 380px; position: fixed; } #gib img { width: 100%; height: auto; } </style> <div id="main"> <img src="https://tombrot.neocities.org/graphics/tomb.gif" class="center"> </div> <div id="gib"><img src="https://tombrot.neocities.org/graphics/gib%20pagedoll.png"></div> </body> </html>
解决方法
问题根源:#gib用了position: fixed(相对于整个浏览器窗口定位)和固定的margin-left: 380px,窗口分辨率变化时,居中的#main位置会相对窗口改变,但#gib的固定值不会跟着变,所以出现偏移。要让#gib跟着#main走,需要修改定位逻辑:
- 调整DOM结构:把
#gib容器放到#main内部,这样它的定位可以以#main为基准:
<div id="main"> <img src="https://tombrot.neocities.org/graphics/tomb.gif" class="center"> <div id="gib"><img src="https://tombrot.neocities.org/graphics/gib%20pagedoll.png"></div> </div>
- 修改CSS样式:
- 给
#main添加position: relative,让内部的绝对定位元素以它为参考 - 把
#gib的position: fixed改成position: absolute,用top和left代替固定margin值,确保它始终在#main的指定角落:
#main { width: 300px; height: 300px; margin: auto; margin-top: 100px; padding: 10px; background-color: aliceblue; box-shadow: 0px 0px 30px 30px aliceblue; position: relative; /* 添加这行 */ } #gib { width: 200px; position: absolute; /* 替换fixed为absolute */ top: -150px; /* 保持原来的垂直偏移量 */ left: calc(100% + 80px); /* 相对于#main的右侧再偏移80px,对应原来的380px(300+80) */ margin: 0; /* 去掉原来的margin */ }
这样修改后,不管窗口分辨率怎么变,#gib都会始终跟着#main的位置走,不会再偏移。
内容的提问来源于stack exchange,提问作者tombrot
相关产品推荐
相关产品推荐

