我想要一个水平的元素列表,包含在一个具有固定宽度的可水平滚动的外部包装器中。外包装有一个相对位置。其中一项包含绝对定位的 div。
滚动外包装时,我希望绿色覆盖层保持在同一位置。我认为 position: absolute 总是相对于具有定义位置的第一个祖先(这将是外部包装器)?
我正在使用 white-space: nowrap 为 #wrapper 获取一行中的元素。
#outer-wrapper {
position: relative;
width: 300px;
height: 150px;
overflow: scroll;
}
#wrapper {
white-space: nowrap;
display: inline-block;
}
#one {
background-color: red;
}
#two {
background-color: blue;
}
.box {
white-space: normal;
display: inline-block;
width: 200px;
height: 150px;
}
.overlay {
background-color: green;
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 40px;
}
<div id="outer-wrapper">
<div id="wrapper">
<div id="one" class="box">
<div class="overlay"></div>
</div>
<div id="two" class="box"></div>
</div>
</div>
我希望标记保持示例中的原样,尽管这并不是完全固定的。
而且我真的无法为水平列表定义固定宽度。
最佳答案
如果我没猜错你的问题,那么只用 HTML 和 CSS 是不可能的。然而,您可以使用 jQuery 实现它,如下所示:
$(function() {
var wrapper = $('#outer-wrapper');
$('#outer-wrapper').scroll(function() {
$('.overlay').css({
'marginLeft': wrapper.scrollLeft()
});
});
});
#outer-wrapper {
position: relative;
width: 300px;
height: 150px;
overflow: scroll;
}
#wrapper {
white-space: nowrap;
display: inline-block;
}
#one {
background-color: red;
}
#two {
background-color: blue;
}
.box {
white-space: normal;
display: inline-block;
width: 200px;
height: 150px;
}
.overlay {
background-color: green;
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outer-wrapper">
<div id="wrapper">
<div id="one" class="box">
<div class="overlay"></div>
</div>
<div id="two" class="box"></div>
</div>
</div>
关于html - 空白 : nowrap seems to affect inner elements position: absolute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38395189/