相对和绝对定位的问题
Problems with relative and absolute positioning
我在实现元素的绝对定位时遇到了一些问题。我正在尝试实现两个横幅广告以在用户滚动 div 时保持静止。我尝试将 parents 位置更改为相对位置,而 children 我想将静态位置更改为绝对位置。这使初始位置正确,但我仍然能够滚动到绝对 divs。这里是合适的 CSS/HTML.
HTML:
<div id="pane1">
<div id="home-banner1" class="banner">
</div>
<div id="home-banner2" class="banner">
</div>
<?php ..... ?>
</div>
CSS:
#pane1{
width:100%;
background-repeat: repeat;
height:auto;
display:inline-block;
padding:20px 50px 50px 50px;
min-height:500px;
text-align:center;
position:relative;
}
.banner{
width:50px;
height:300px;
background-color:white;
position:absolute;
top:0;
}
#home-banner1{
left:0;
}
#home-banner2{
right:0;
}
对横幅使用 position:fixed;
,这样即使您向上或向下滚动页面,它也会停留在屏幕上的固定位置。
编辑
要仅在 #container
元素下方隐藏和显示横幅,您可以像这样使用一些 jQuery:
$(window).scroll(function() {
var top_div_height = $('#container').height(); // height of the blue top container
if ($(this).scrollTop() < top_div_height) { // hide the rightside banner if the user is viewing that blue top container
$('#home-banner2').css({
'display': 'none'
});
}
else{ //... otherwise show the rightside banner
$('#home-banner2').css({
'display': 'block'
});
}
});
确保为 #home-banner2
元素设置 CSS 规则 position:fixed;
。
希望这会有所帮助。
实际上您的代码完全符合预期。
Position: absolute
相对于具有 position: relative
的最近父元素移动元素。因此,如果父元素超出视口,子绝对元素也会超出视口。
为了获得想要的结果,您需要一些 javascript/jquery 来在父元素进入视口时修复元素,并在父元素离开时 'unfix' 修复元素。
我在实现元素的绝对定位时遇到了一些问题。我正在尝试实现两个横幅广告以在用户滚动 div 时保持静止。我尝试将 parents 位置更改为相对位置,而 children 我想将静态位置更改为绝对位置。这使初始位置正确,但我仍然能够滚动到绝对 divs。这里是合适的 CSS/HTML.
HTML:
<div id="pane1">
<div id="home-banner1" class="banner">
</div>
<div id="home-banner2" class="banner">
</div>
<?php ..... ?>
</div>
CSS:
#pane1{
width:100%;
background-repeat: repeat;
height:auto;
display:inline-block;
padding:20px 50px 50px 50px;
min-height:500px;
text-align:center;
position:relative;
}
.banner{
width:50px;
height:300px;
background-color:white;
position:absolute;
top:0;
}
#home-banner1{
left:0;
}
#home-banner2{
right:0;
}
对横幅使用 position:fixed;
,这样即使您向上或向下滚动页面,它也会停留在屏幕上的固定位置。
编辑
要仅在 #container
元素下方隐藏和显示横幅,您可以像这样使用一些 jQuery:
$(window).scroll(function() {
var top_div_height = $('#container').height(); // height of the blue top container
if ($(this).scrollTop() < top_div_height) { // hide the rightside banner if the user is viewing that blue top container
$('#home-banner2').css({
'display': 'none'
});
}
else{ //... otherwise show the rightside banner
$('#home-banner2').css({
'display': 'block'
});
}
});
确保为 #home-banner2
元素设置 CSS 规则 position:fixed;
。
希望这会有所帮助。
实际上您的代码完全符合预期。
Position: absolute
相对于具有 position: relative
的最近父元素移动元素。因此,如果父元素超出视口,子绝对元素也会超出视口。
为了获得想要的结果,您需要一些 javascript/jquery 来在父元素进入视口时修复元素,并在父元素离开时 'unfix' 修复元素。