【问题标题】:Problems with relative and absolute positioning相对定位和绝对定位的问题
【发布时间】:2019-10-01 16:55:09
【问题描述】:

我在元素上实现绝对定位时遇到了一些问题。我试图实现两个横幅广告以在用户滚动 div 时保持静止。我尝试将父母位置更改为相对位置,将我想保持静态位置的孩子位置更改为绝对位置。这得到了正确的初始位置,但我仍然能够滚动过去绝对 div。这是适当的 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;
}

【问题讨论】:

标签: html css css-position


【解决方案1】:

为横幅使用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;

希望这会有所帮助。

【讨论】:

  • 嗨 Akhilesh,我试过了,但它会将横幅固定到 DOM 的顶部,而不是 'pane1' div。
  • 谢谢,这正是我想要的!
【解决方案2】:

实际上,您的代码完全按照预期工作。

Position: absolute 相对于position: relative 的最近父元素移动元素。因此,如果父元素超出视口,子绝对元素也会如此。

要获得想要的结果,您需要一些 javascript/jquery 来修复元素,因为它的父元素进入视口并在父元素离开时“取消修复”。

类似于Bootstraps' affix的东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多