将div粘贴到另一个绝对定位的溢出滚动div的顶部

时间:2013-11-02 15:36:29

标签: css html css-position

这就是事情,有一个div .page绝对定位于页面。在里面,有一个.container div,在容器中有.content个。

.page具有一定的高度,因此,内容将在.page内滚动。在这种情况下,我希望.stuck div保持在.page的顶部。 (我确信我在上面犯了语法错误!)

无论如何,fiddel:

http://jsfiddle.net/YBAvb/

更新:我希望.stuck固定在.page的顶部,无论.page上的滚动如何。

这是布局:

<div class="page">
    <div class="container">
        <div class="content"></div>
        <div class="stuck"></div>
    </div>
</div>

和我的(不工作)css:

.page{
    position: absolute;
    top:50px;
    left:200px;
    width:200px;
    height:300px;
    overflow:auto;
}
.container{
    position:relative;
}
.stuck{
    position: absolute;
    top:0;
    right:0;
    left:0;
    height:50px;
    background:blue;
}
.content{
    height:700px;
    background:gray;
}

我希望.stuck div顶部的蓝色.page div 始终存在。有什么帮助吗?

更新 注意:一个快速的伎俩可能是使.stuck成为positions:fixed并且.page的位置和宽度相同,但这不是我自{{1}的坐标以来的回答随时可能会随着JS而改变。

2 个答案:

答案 0 :(得分:4)

您可以将.page.stuck添加到公共父元素,并将其覆盖在另一个元素上。

http://jsfiddle.net/YBAvb/1/

    .page_holder{
        position: absolute;
        top:50px;
        left:200px;
        width:200px;
        height:300px;
    }
    .page {
        position: absolute;
        top:0;
        left:0;
        width:200px;
        height:300px;
        overflow:auto;
        z-index: 1;
    }
    .container {
        position:relative;
    }
    .stuck {
        position: absolute;
        top:0;
        right:0;
        left:0;
        height:50px;
        background:blue;
        margin-right: 18px;
        z-index: 2;
    }
    .content {
        height:700px;
        background:gray;
    }
    <div class="page_holder">
        <div class="stuck"></div>
        <div class="page">
            <div class="container">
                <div class="content"></div>
            </div>
        </div>
    </div>

答案 1 :(得分:1)

  

因为.page的坐标可能随时随JS而改变。

...所以你已经使用了JS! :)

使用这个确切的HTML标记不可能
对于这种情况,我们总是使用Javascript和jQuery:JSBIN DEMO

$('.stuck').each(function(){

  var $that = $(this),
      $page = $that.closest('.page');

  $page.scroll(function(){      
    $that.css({top: this.scrollTop});
  });

});