浏览器缩放时图片被裁切?容器高度不足时顶部图片无法滚动的解决方法
解决方法
问题出在哪
你给图片加了position: relative; top: -20px,把它往上挪出了浅蓝色容器的顶部范围,但容器默认没开滚动功能,超出的部分直接被裁掉,自然看不到也没法往上滚着看。
方案一:用margin偏移替代relative定位(推荐)
这种方式更贴合正常布局逻辑,不会出现元素脱离文档流的问题:
body { display: flex; justify-content: center; height: 100vh; align-items: center; } .box { background: lightblue; width: 300px; height: 500px; min-height: 300px; overflow-y: auto; /* 开启垂直滚动 */ padding-top: 20px; /* 给容器内部内容留出顶部空间,避免被图片挡住 */ } img { margin-top: -20px; /* 用margin代替relative的top偏移,实现向上挪的效果 */ margin-left: 120px; }
方案二:保留relative定位,调整容器属性
如果一定要保留relative定位,给容器加滚动和内边距,让溢出的图片区域能被滚动到:
body { display: flex; justify-content: center; height: 100vh; align-items: center; } .box { background: lightblue; width: 300px; height: 500px; min-height: 300px; overflow-y: auto; /* 开启垂直滚动 */ padding-top: 20px; /* 扩展容器的可滚动范围,把图片偏移的部分包含进来 */ } img { position: relative; top: -20px; left: 120px; }
方案三:改用绝对定位固定图片位置
要是想让图片始终贴着容器顶部偏移,又不影响容器内其他元素布局,可以用绝对定位:
body { display: flex; justify-content: center; height: 100vh; align-items: center; } .box { background: lightblue; width: 300px; height: 500px; min-height: 300px; overflow-y: auto; /* 开启垂直滚动 */ position: relative; /* 让容器成为图片绝对定位的参考父级 */ padding-top: 30px; /* 给容器内的内容留出顶部空间 */ } img { position: absolute; top: -20px; left: 120px; }
不管用哪种方案,只要开启容器的垂直滚动,同时让图片的偏移区域被包含在可滚动范围内,就能解决容器缩小时看不到图片、没法滚动的问题。
内容的提问来源于stack exchange,提问作者pvs karthikeya
相关产品推荐
相关产品推荐

