滚动列表div箭头定位异常:absolute子元素偏移问题求助
解决可滚动列表中箭头定位错误的问题
你创建的可滚动div列表中,只有第一个div的四边箭头显示正常,其余div的顶部和底部箭头都偏移到了页面的顶部/底部位置。
问题原因
你的箭头元素使用了position: absolute,但它们的父容器.collection没有设置定位上下文(即position: relative),导致所有绝对定位的箭头都会相对于整个文档(body)进行定位,而不是各自的父容器。
修正后的代码
CSS代码
.collection { height: 100vh; width: 100vw; position: relative; /* 添加定位上下文,让内部绝对定位元素以当前容器为参照 */ } .leftArrow { background: blue; position: absolute; left: 0px; height: 100%; /* 改为100%,匹配父容器高度 */ width: 5vw; } .rightArrow { /* 修正拼写错误:rigthArrow → rightArrow */ background: blueviolet; position: absolute; height: 100%; /* 改为100%,匹配父容器高度 */ right: 0px; width: 5vw; } .topArrow { background: grey; position: absolute; top: 0px; left: 5vw; height: 5vh; width: 90vw; } .bottomArrow { background: firebrick; position: absolute; bottom: 0px; left: 5vw; height: 5vh; width: 90vw; } body { margin: 0px; -ms-overflow-style: none; scrollbar-width: none; } ::-webkit-scrollbar { display: none; }
HTML代码
<div id="gallery"> <div class="collection" style="background-color: greenyellow;"> <div class="leftArrow"></div> <div class="rightArrow"></div> <div class="bottomArrow"></div> <div class="topArrow"></div> </div> <div class="collection" style="background-color: antiquewhite;"> <div class="leftArrow"></div> <div class="rightArrow"></div> <div class="bottomArrow"></div> <div class="topArrow"></div> </div> <div class="collection" style="background-color: black;"> <div class="leftArrow"></div> <div class="rightArrow"></div> <div class="bottomArrow"></div> <div class="topArrow"></div> </div> </div>
修改说明
- 给
.collection添加position: relative,为内部绝对定位元素提供定位参照,确保箭头相对于各自的父容器定位。 - 将左右箭头的
height: 100vh改为height: 100%,让箭头高度与父容器高度保持一致。 - 修正类名拼写错误
rigthArrow为rightArrow,避免样式失效。
内容的提问来源于stack exchange,提问作者Bero Rero
相关产品推荐
相关产品推荐

